You are given a 16-bit BMP image represented by an array of pixel values, where most of the image is black, but there is a white rectangle somewhere within the black pixels. The pixel values for the black pixels are between 700 and 750, and the white pixels (which form a rectangle) have pixel values between 920 and 980, reflecting varying lighting conditions.
How can you differentiate between the black and white pixels with certainty?
Given the image's width, height, and array of pixel values, write a function to return the coordinates of the rectangle's corners (top-left and bottom-right).
Solution:
Step 1: Determine a Threshold for Differentiating Black and White
Since the black pixels fall within a known range (700-750) and the white pixels are within a higher range (920-980), we can calculate a threshold to reliably differentiate between black and white pixels.
Median Approach: To find a robust threshold, we calculate the median of the known black and white pixel values.
Black pixel range: [700, 750]
White pixel range: [920, 980]
The median of this range will give us a value that divides the two groups:
Median = 750 (This is our threshold).
Step 2: Identify the White Pixels (Rectangle)
Iterate through the pixel array, checking if each pixel value exceeds the threshold (750 in this case).
For each white pixel:
Calculate its
𝑥
,
𝑦
x,y coordinates in the image.
Track the bounds of the white rectangle using the min and max values for both x and y coordinates.
Step 3: Return the Rectangle's Corners
After processing all white pixels, the bounds (minX, maxX, minY, maxY) will represent the top-left and bottom-right corners of the white rectangle.
public static int[] findRectangleCorners(int width, int height, int[] pixels) {
int minX = Integer.MAX_VALUE, maxX = -1, minY = Integer.MAX_VALUE, maxY = -1;
// Calculate the threshold for white pixels (750 as median)
int threshold = 750;
// Iterate through all pixels to find the white ones
for (int i = 0; i < pixels.length; i++) {
if (pixels[i] > threshold) { // White pixel
int x = i % width;
int y = i / width;
// Update the rectangle bounds
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
}
// Return the coordinates of the top-left and bottom-right corners
return new int[] {minX, minY, maxX, maxY};
}