CSE 131 Module 3: Iteration


Bridge: Iteration and Array Structures

Digital filtering of images

A two dimensional digital filter is a square array of filter coefficients. It is used to compute a new value for each pixel of an image by taking into account the values of the neighboring pixels, using a weighted average. Applying a filter to an image can acheive a smoothing effect, softening the overall image by blurring the pixels together. Consider the following array of filter coefficients for a 3x3 filter:
double[][] coefs = { // 3x3 array of filter coefficients
     { .0625, .125, .0625 }, 
     { .125,  .25,  .125  }, 
     { .0625, .125, .0625 } 
Your job is to write a method for RasterTool (module 3 code) that takes in two Image objects as parameters, applies the filter to every pixel in the first image (except the pixels along the outer border of the image) and puts the result in the second image. Conceptually, to compute the pixel color for the resulting image, think about centering the 3x3 filter over a pixel (x,y) of the first image. In other words, the 3x3 filter will be (conceptually) laying on top of a region of 9 pixels, with (x,y) at its center. You will multiply each filter coefficient by the corresponding pixel in the image, and sum these results to produce the weighted average of the center pixel and its neighbors. You'll put the result in the pixel in the second image. Then, you'll "slide" the filter over to be centered on the next pixel. This pdf file illustrates an example of computing the value one pixel. Of course, you won't write out all the terms, but instead will write nested loops to do the computation.

Because each pixel really has three components, you'll actually need to do this for each color component (red, green, and blue) and then call the Color constructor to create the new color for the resulting image. If the sum exceeds 255, just make that component be 255. (Recommendation: Split up the work into several methods using top-down design.)

Test your filter in NIP. The resulting image should be less "sharp" that the original. To apply the filter again, you can switch the source and target panels, and then run your method again. By going back and forth like this, you can see the effect of applying the filter repeatedly to the same image. The image should be recognizable, but get blurrier each time.

Your solution must use arrays and iteration over arrays, or you will not receive credit.