## ConvolveOp

The `ConvolveOp` is the most complicated `BufferedImageOp` but also the most versatile. It is the only `BufferedImageOp` you should master and know by heart. A `ConvolveOp` is used to perform a convolution from the source image to the destination. If you never took any math courses, or more likely, if you forgot everything about what you learned during those classes, a convolution is a spatial operation that computes the destination pixel by multiplying the source pixel and its neighbors by a convolution kernel.^{1} Don't be frightened: You will soon understand what this gobbledygook means.

Any convolution operation relies on a convolution kernel, which is just a matrix of numbers. Here is an example:

The kernel defined here represents a 3 x 3 matrix of floating-point numbers. When you perform a convolution operation, this matrix is used as a sliding mask over the pixels of the source image. For instance, to compute the result of the convolution for a pixel located at the coordinates (*x*, *y*) in the source image, the center of the kernel is positioned at these coordinates. In the case of a 3 x 3 kernel, here are the coordinates, in the source image, of the pixels that each corresponding kernel value is applied to:

To compute the value of the destination pixel at (*x*, *y*), Java 2D multiplies the kernel values with their corresponding color values in the source image. Imagine a 3 x 3 white image with a single black pixel in its center, as suggested in Figure 8-6.

Figure 8-6 A black pixel surrounded by white pixels. The numbers show the RGB value of each pixel.

To convolve the black pixel with our 3 x 3 kernel, we must start by placing the matrix over the pixels, as shown in Figure 8-7.

Figure 8-7 Each color value is multiplied by the corresponding value of the kernel.

Now we can compute all the multiplications, add up the results, and get the color value of the destination pixel:

The destination pixel is therefore a light gray; its RGB value is (227, 227, 227), or #E3E3E3. By now, you might have guessed what this kernel does: It replaces each pixel by the average color of its surroundings. Such a convolution operation is commonly known as a blur. We discuss blurring filters in more detail in Chapter 16, "Static Effects."

### Constructing a Kernel

There are no particular restrictions about the size and contents of the kernels you can use with Java 2D. However, you should be aware of several important characteristics of kernels.

First, the values of a kernel should add up to 1.0 in the typical case, as in the previous example where all nine entries have the value 1/9. If these values do not add up to 1.0, the luminosity of the picture will not be preserved. This can, however, be turned to your advantage. For instance, you can increase the luminosity of a picture by 10 percent with a 1 x 1 kernel containing the value 1.1. Similarly, you can darken a picture by 10 percent with a 1 x 1 kernel containing the value 0.9. When dealing with larger kernels, the sum of the values defines the new luminosity. For instance, if the sum equals 0.5, then the luminosity will be cut in half. Keep that in mind when creating a kernel.

The size of a kernel defines the strength of a filter. For instance, a 3 x 3 blurring kernel produces a slightly blurry picture, whereas a 40 x 40 blurring kernel produces an indistinguishable blob from the original image.

The dimensions of the kernel are equally important. Kernels are usually odd-sided. While it is perfectly safe to use a 4 x 4 or a 12 x 12 kernel, it is not recommended. An even-sided kernel will not be centered over the source pixel and might give unbalanced visual results, which you should avoid. Also, it is easier for code readers to understand how an odd-sided kernel will behave. The Java 2D documentation defines the value of the matrix used as the center of the kernel as being the one at the coordinates (w – 1)/2, (h – 1)/2. This definition makes it harder to know which value is used as the center.

Your kernels do not have to be square shaped. Vertical kernels, for example with a 1 x 5 matrix, and horizontal kernels, for example with a 5 x 1 matrix, can be used to apply effects that work in only one direction. Chapter 16 presents examples of such kernels.

Last but not least, avoid using large kernels. When convolving a picture with a 3 x 3 kernel, Java 2D performs at least 17 operations (9 multiplications and 8 additions) per color component per pixel. Convolving a 640 x 480 picture requires at least 640 x 480 x 3 x 17 = 15,667,200 operations! That's quite a lot.^{2} And this number does not even include the operations of reading and writing the actual pixel values from and to the source and destination pictures. We therefore strongly advise you not to perform convolve operations at painting time. Instead perform the operations once prior to painting and cache the results instead.

No matter what kernel you create, writing the code to perform the convolution is simple:

BufferedImage dstImage = null; float[] sharpen = new float[] { 0.0f, -1.0f, 0.0f, -1.0f, 5.0f, -1.0f, 0.0f, -1.0f, 0.0f }; Kernel kernel = new Kernel(3, 3, sharpen); ConvolveOp op = new ConvolveOp(kernel); dstImage = op.filter(sourceImage, null);

In Java 2D, a kernel is an array of floats and two dimensions. In this case, we use a 3 x 3 sharpening kernel to create an array of nine floats and tell the `Kernel` class that we want this array to be treated as a 3 x 3 matrix.

Figure 8-8 shows the result of the convolution with the 3 x 3 sharpening kernel shown in the previous code example.

Figure 8-8 The sharpened picture shows enhanced details.

### Working on the Edge

Everything is not perfect yet. Take a close look at the generated result: You should see a black border surrounding the picture. During the convolve operation, Java 2D always matches the center of the kernel with one pixel of the source image. This works well for every pixel except the ones on the edges of the picture. Try to line up a 3 x 3 kernel with any pixel on the edge of an image and you will see that some parts of the kernel lie outside of the image. To work around this problem, Java 2D replaces the pixels it cannot compute with black pixels, which results in darkened edges because of the extra black introduced into the convolve operations for these edge pixels. To avoid this result, you can instruct Java 2D to do nothing and to keep the original color:

// the default is ConvolveOp.EDGE_ZERO_FILL // the last parameter is the RenderingHints set ConvolveOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);

Unfortunately, neither of these solutions generates good-looking results. To get rid of any problem on the edges, you can simply increase the size of the original picture, as follows:

int kernelWidth = 3; int kernelHeight = 3; int xOffset = (kernelWidth – 1) / 2; int yOffset = (kernelHeight – 1) / 2; BufferedImage newSource = new BufferedImage( sourceImage.getWidth() + kernelWidth – 1, sourceImage.getHeight() + kernelHeight – 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = newSource.createGraphics(); g2.drawImage(sourceImage, xOffset, yOffset, null); g2.dispose(); ConvolveOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); dstImage = op.filter(newSource, null);

The original image is drawn centered into a new, larger, transparent image. Because we added enough transparent pixels on each side of the original image, the convolution operation will not affect the pixels of the original image. It is important to use the `ConvolveOp.EDGE_NO_OP` edge condition so you will keep the pixels transparent around the image. This technique of adding transparent pixels on the sides provides better-looking results, but you have to take the extraneous pixels into account.