/** * @author Pacien TRAN-GIRARD * @author Timothée FLOURE */ public final class Filter { /** * Get a pixel without accessing out of bounds * * @param gray a HxW float array * @param row Y coordinate * @param col X coordinate * @return nearest valid pixel color */ public static float at(float[][] gray, int row, int col) { int maxRow = gray.length - 1; int maxCol = gray[0].length - 1; if (row < 0) row = 0; if (col < 0) col = 0; if (row > maxRow) row = maxRow; if (col > maxCol) col = maxCol; return gray[row][col]; } /** * Convolve a single-channel image with specified kernel. * * @param gray a HxW float array * @param kernel a MxN float array, with M and N odd * @return a HxW float array */ public static float[][] filter(float[][] gray, float[][] kernel) { int width = gray[0].length; int height = gray.length; float[][] filteredImage = new float[height][width]; for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { float pixelCore[][] = { {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++) { filteredImage[row][col] += kernel[i][j] * pixelCore[i][j]; } } } } return filteredImage; } /** * Smooth a single-channel image * * @param gray a HxW float array * @return a HxW float array */ public static float[][] smooth(float[][] gray) { float smoothCore[][]={ {0.1f,0.1f,0.1f}, {0.1f,0.2f,0.1f}, {0.1f,0.1f,0.1f} }; float[][] smoothtImage = Filter.filter(gray, smoothCore); return smoothtImage; } /** * Compute horizontal Sobel filter * * @param gray a HxW float array * @return a HxW float array */ public static float[][] sobelX(float[][] gray) { float sobelXCore[][]= { {-1,0,1}, {-2,0,2}, {-1,0,1} }; float[][] sobelXImage = Filter.filter(gray, sobelXCore); return sobelXImage; } /** * Compute vertical Sobel filter * * @param gray a HxW float array * @return a HxW float array */ public static float[][] sobelY(float[][] gray) { float sobelYCore[][]={ {-1,-2,-1}, {0,0,0}, {1,2,1} }; float[][] sobelYImage = Filter.filter(gray, sobelYCore); System.out.println(sobelYImage[0][0]); return sobelYImage; } /** * Compute the magnitude of combined Sobel filters * * @param gray a HxW float array * @return a HxW float array */ public static float[][] sobel(float[][] gray) { float[][] x = Filter.sobelX(gray); float[][] y = Filter.sobelY(gray); int width = gray[0].length; int height = gray.length; float[][] sobelImage = new float[height][width]; for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { sobelImage[row][col] = (float) Math.sqrt(Math.pow(x[row][col],2)+Math.pow(y[row][col],2)); } } return sobelImage; } }