Topic 1 - Variables and Data Types
Topic 2 - Conditionals and Strings
Topic 3 - Loops
Topic 4 - Arrays
Topic 5 - File Handling
Semester 1 Projects
Topic 6 - Classes/Objects and Methods
Topic 7 - ArrayLists
Semester Projects

Part 1f: Blur

In this method you should implement a filter to blur an image. One way to do this is to create a new image whose pixel values are averaged with the values of their immediate neighbors from the source image; this simulates a “blurring” effect between pixels.

The general idea is that for a given pixel (r, c) located at row r and column c in the source image, you will change its red, green, and blue components to be the average (rounded down to the nearest integer) of the nine red, green, and blue components in the pixels at locations (r-1, c-1) through (r+1, c+1).

For example, in the diagram below, the pixel (row 1, column 2) should be modified to store the average of the nine pixels (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), and (2, 3). These are the eight neighbors of (1, 2) as well as (1, 2) itself. So the red part of (1, 2) would be changed from 32 to (84+74+16+66+32+95+28+47+31)/9 = 52. The green component would be changed from 67 to (22+38+17+53+67+65+49+21+41)/9 = 41. The blue component would be changed from 12 to (99+69+18+88+12+35+31+94+51)/9 = 55.

Therefore the overall pixel value at (1, 2) in the result image would be (52, 41, 55).

A special case is the set of pixels along the edges of the image. When blurring those pixels, they do not have eight neighbors like other pixels do, so the average includes fewer data points. For example, in the diagram above, the pixel at (0, 0) has no neighbors above or left of it, so it should become the average of the four pixels (0, 0), (0, 1), (1, 0), and (1, 1). So the red component of (0, 0) would become (14+84+21+66)/4 = 46, and so on.

The pixel at (3, 3) has no neighbors below it, so it should become the average of the six pixels (2, 2), (2, 3), (2, 4), (3, 2), (3, 3), and (3, 4). The red component of (3, 3) would become (47+31+246+15+60+188)/6 = 97, and so on. Take care that your algorithm does not crash by trying to access outside the bounds of the array.

A common bug in this algorithm is to try to modify the pixel array in-place. You should not do this; you should create a new second pixel array to store the result image’s pixels. The reason is because you don’t want modifications made to one pixel to impact another pixel in the same pass over the array. In our previous example, we already stated that pixel (1, 2) should be changed from (32, 67, 12) to (52, 41, 55). But if you store (52, 41, 55) into this pixel and then use that value for further calculations on pixels in the same pass over the array, their averages will be incorrect. For example, when computing the average for pixel (1, 3), the pixel (1, 2) is one of its neighbors. But you should use that pixel’s original value of (32, 67, 12) when computing that average.