Linear blur filter demo in Java
The Java code below implements a simple linear blur filter for images. Its main purpose is to demonstrate the access and manipulation of pixels in an image object. The filter algorithm itself lacks any optimizations and is pretty inefficient.
The methods blurGrayscaleImage()
and blurRgbImage()
return a filtered copy of the passed grayscale or RGB image, respectively. They both rely on the method blurSingleBand()
which does the actual filtering for a specified band of the image. It calculates the arithmetic mean of the pixel values within the filter window and writes that value to the position located at the center of the filter window in the output image.
import java.awt.image.BufferedImage; public class LinearBlurFilter { private final int filterSize; public LinearBlurFilter(int filterSize) { super(); this.filterSize = filterSize; } public BufferedImage blurGrayscaleImage(BufferedImage img) { assert img.getRaster().getNumBands() == 1; BufferedImage blurredImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); blurSingleBand(img, blurredImg, 0); return blurredImg; } public BufferedImage blurRgbImage(BufferedImage img) { assert img.getRaster().getNumBands() == 3; BufferedImage blurredImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR); blurSingleBand(img, blurredImg, 0); blurSingleBand(img, blurredImg, 1); blurSingleBand(img, blurredImg, 2); return blurredImg; } private void blurSingleBand(BufferedImage imgIn, BufferedImage imgOut, int band) { assert filterSize > 2; assert (filterSize % 2) == 1; int filterOverlap = (filterSize - 1) / 2; for (int x = 0; x < imgIn.getWidth(); x++) { for (int y = 0; y < imgIn.getHeight(); y++) { int filterValueSum = 0; int filterPixelCnt = 0; for (int i = x - filterOverlap; i <= x + filterOverlap; i++) { for (int j = y - filterOverlap; j <= y + filterOverlap; j++) { if ((0 <= i && i < imgIn.getWidth()) && (0 <= j && j < imgIn.getHeight())) { filterValueSum += imgIn.getRaster().getSample(i, j, band); filterPixelCnt++; } } } int targetPixelValue = filterValueSum / filterPixelCnt; imgOut.getRaster().setSample(x, y, band, targetPixelValue); } } } }