package domain.image.processing.outline; import domain.image.GrayScaleMatrix; import domain.image.Image; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.imgproc.Imgproc; public class LinearOutline { public static GrayScaleMatrix prewittGradient(Image image, int direction) { Mat kernel = new Mat(3, 3, CvType.CV_64F); if (direction == 1) { kernel.put(0, 0, -1, -1, -1, 0, 0, 0, 1, 1, 1); } else if (direction == 2) { kernel.put(0, 0, -1, 0, 1, -1, 0, 1, -1, 0, 1); } else { kernel.release(); throw new IllegalArgumentException("Direction must be 1 or 2"); } return applyKernel(image, kernel); } public static GrayScaleMatrix sobelGradient(Image image, int direction) { Mat kernel = new Mat(3, 3, CvType.CV_64F); if (direction == 1) { kernel.put(0, 0, -1, -2, -1, 0, 0, 0, 1, 2, 1); } else if (direction == 2) { kernel.put(0, 0, -1, 0, 1, -2, 0, 2, -1, 0, 1); } else { kernel.release(); throw new IllegalArgumentException("Direction must be 1 or 2"); } return applyKernel(image, kernel); } public static GrayScaleMatrix laplacian4(Image image) { Mat kernel = new Mat(3, 3, CvType.CV_64F); kernel.put(0, 0, 0, -1, 0, -1, 4, -1, 0, -1, 0); return applyKernel(image, kernel); } public static GrayScaleMatrix laplacian8(Image image) { Mat kernel = new Mat(3, 3, CvType.CV_64F); kernel.put(0, 0, -1, -1, -1, -1, 8, -1, -1, -1, -1); return applyKernel(image, kernel); } private static GrayScaleMatrix applyKernel(Image image, Mat kernel) { GrayScaleMatrix gray = image.toGrayScale(); Mat input = new Mat(gray.getHeight(), gray.getWidth(), CvType.CV_64F); double[][] data = gray.getRawData(); for (int y = 0; y < gray.getHeight(); y++) { input.put(y, 0, data[y]); } Mat result = new Mat(); Imgproc.filter2D(input, result, CvType.CV_64F, kernel); double[][] output = new double[result.rows()][result.cols()]; for (int y = 0; y < result.rows(); y++) { result.get(y, 0, output[y]); } input.release(); result.release(); kernel.release(); return new GrayScaleMatrix(output); } }