6.5. Combining Pixels: BlurringWhen we make pictures larger (scaling them up), we usually get rough edges: Sharp steps to lines, which we call pixelation. We can reduce pixelation by blurring the image. What we do is set each pixel to an average of pixels around it. In this example, we go through all pixels (note the large loop that surrounds everything) and then in the X and Y dimensions, compute the average of the pixels to either side of the pixel. It takes a picture, and a number (size) of pixels to compute the average. Of course we need to be careful not to try and access pixels beyond the allowed values of the two-dimensional array of pixels. Try this in the interactions pane: > String fileName = FileChooser.getMediaPath("caterpillar.jpg"); > Picture p = new Picture(fileName); The java.lang.ArrayIndexOutOfBoundsException tells us that we tried to access an array element that was outside the allowed indices. If this happens when our program is executing, the program will stop and report the exception. This is called a run-time exception because it happens when the program is running rather than at compile time. So how do we check that the index values are acceptable? We know that the x indices range from 0 to width 1 and the y indices range from 0 to height 1. So we can use x >= 0 && x < this.getWidth() && y >= 0 && y < this.getHeight()). Program 42. A Simple Blur |
/** * Method to blur the pixels * @param numPixels the number of pixels to average in all * directions so if the numPixels is 2 then we will average * all pixels in the rectangle defined by 2 before the * current pixel to 2 after the current pixel */ public void blur(int numPixels) { Pixel pixel = null; Pixel samplePixel = null; int redValue = 0; int greenValue = 0; int blueValue = 0; int count = 0; |
Here is how to use this method:
> Picture p = new Picture( FileChooser.getMediaPath("flower1.jpg")); > p = p.scaleUp(2); > p.explore(); > p.blur(2); > p.explore();
Figure 6.13 shows the flower from the collage made bigger, then blurred. You can see the pixelation in the bigger versionthe sharp, blocky edges. With the blur, some of that pixelation goes away. More careful blurs take into account regions of colors (so that edges between colors are kept sharp), and thus are able to reduce pixelation without removing sharpness.