This question involves manipulating a 2D array of integers that represents a grayscale image. You will write two methods for the Image class, which is partially defined below.
public class Image {
private int[][] pixels;
/**
* The pixels array is initialized in the constructor with integer values
* from 0 (black) to 255 (white), inclusive. The array is rectangular
* (all rows have the same length) and has at least one row and one column.
*/
public Image(int[][] pixelData) {
pixels = pixelData;
}
/**
* Brightens every pixel in the image.
* to be implemented in part (a)
*/
public void brighten(int amount) {
/* to be implemented in part (a) */
}
/**
* Calculates the average pixel value in a specified square region.
* to be implemented in part (b)
*/
public double getRegionAverage(int row, int col) {
/* to be implemented in part (b) */
return 0.0; // placeholder
}
// Other methods not shown.
}
Write the brighten method.
This method increases the value of every pixel in the pixels grid by the given amount. There is an upper limit for pixel values: a pixel's value cannot exceed 255. If adding amount to a pixel's value would cause it to exceed 255, its new value should be set to 255.
Example:
If pixels is {{10, 250}, {100, 200}} and brighten(20) is called, the pixels array should be modified to become {{30, 255}, {120, 220}}.
Write the getRegionAverage method.
This method calculates and returns the average value of all pixels in the 3x3 square region centered at the given row and col. The 3x3 region includes the center pixel at (row, col) and its eight immediate neighbors.
The method must correctly handle edge cases where the 3x3 region extends beyond the boundaries of the pixels grid. In such cases, only the pixels that are actually within the grid's bounds should be included in the calculation of the average. The average is the sum of the values of the valid pixels in the region divided by the number of valid pixels in that region.
Example:
Consider the following pixels grid:
{{10, 20, 30},
{40, 50, 60},
{70, 80, 90}}
- A call to
getRegionAverage(1, 1) should consider all 9 pixels, and the average is (10+20+30+40+50+60+70+80+90)/9 = 50.0.
- A call to
getRegionAverage(0, 0) should consider the 4 pixels in the top-left corner (10, 20, 40, 50), and the average is (10+20+40+50)/4 = 30.0.
- A call to
getRegionAverage(2, 1) should consider the 6 pixels in the bottom-middle region, and the average is (40+50+60+70+80+90)/6 = 65.0.