From 2db512ac95a782f6bb35b7c45475a33f73b6f252 Mon Sep 17 00:00:00 2001 From: Timothee Floure Date: Wed, 28 Oct 2015 11:15:28 +0100 Subject: Filter : allow to handle any kernel size (H*N : H and N odd) --- src/main/java/Filter.java | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/main/java/Filter.java b/src/main/java/Filter.java index 4e06800..7e55f04 100644 --- a/src/main/java/Filter.java +++ b/src/main/java/Filter.java @@ -51,17 +51,36 @@ public final class Filter { public static float[][] filter(float[][] gray, float[][] kernel) { int width = gray[0].length; int height = gray.length; + + int kernelWidth = kernel[0].length; + int kernelHeight = kernel.length; + + float pixelNeighbors[][] = new float[kernelHeight][kernelWidth]; float[][] filteredImage = new float[height][width]; + for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { - float pixelNeighbors[][] = { - {Filter.at(gray, row - 1, col - 1), Filter.at(gray, row - 1, col), Filter.at(gray, row - 1, col + 1)}, - {Filter.at(gray, row, col - 1), Filter.at(gray, row, col), Filter.at(gray, row, col + 1)}, - {Filter.at(gray, row + 1, col - 1), Filter.at(gray, row + 1, col), Filter.at(gray, row + 1, col + 1)} - }; - - for (int i = 0; i < kernel[0].length; i++) { - for (int j = 0; j < kernel.length; j++) { + + int pixelRow = -kernelHeight / 2; + int pixelCol = -kernelWidth / 2; + + for (int kernelRow = 0; kernelRow < kernelWidth; kernelRow++) { + for (int kernelCol = 0; kernelCol < kernelHeight; kernelCol++) { + pixelNeighbors[kernelRow][kernelCol] = Filter.at(gray, row + pixelRow, col + pixelCol); + + pixelCol += 1; + if (pixelCol > kernelWidth / 2) { + pixelCol = -kernelWidth / 2; + } + } + pixelRow += 1; + if (pixelRow > kernelHeight / 2) { + pixelRow = -kernelHeight / 2; + } + } + + for (int i = 0; i < kernelWidth; i++) { + for (int j = 0; j < kernelHeight; j++) { filteredImage[row][col] += kernel[i][j] * pixelNeighbors[i][j]; } } -- cgit v1.2.3