Java DIP - Prewitt 算子
Prewitt 算子用于图像中的边缘检测。它检测两种类型的边缘:垂直边缘和水平边缘。
我们使用 OpenCV 函数 filter2D 将 Prewitt 算子应用于图像。它可以在 Imgproc 包下找到。它的语法如下 −
filter2D(src, dst,depth, kernel, anchor, delta, BORDER_DEFAULT);
函数参数如下 −
Sr.No. | 参数 &描述 |
---|---|
1 |
src 源图像。 |
2 |
dst 目标图像。 |
3 |
depth dst的深度。负值(例如 -1)表示深度与源相同。 |
4 |
kernel 它是要扫描图像的内核。 |
5 |
anchor 它是锚点相对于其内核的位置。位置点 (-1, -1) 默认表示中心。 |
6 |
delta 它是在卷积期间要添加到每个像素的值。默认情况下为 0。 |
7 |
BORDER_DEFAULT 我们默认使用此值。 |
除了 filter2D 方法外,Imgproc 类还提供了其他方法。它们简要描述如下 −
Sr.No. | 方法 &描述 |
---|---|
1 |
cvtColor(Mat src, Mat dst, int code, int dstCn) 它将图像从一个颜色空间转换为另一个颜色空间。 |
2 |
dilate(Mat src, Mat dst, Mat kernel) 它使用特定的结构元素来扩大图像。 |
3 |
equalizeHist(Mat src, Mat dst) 它均衡直方图灰度图像。 |
4 |
filter2D(Mat src, Mat dst, intdepth, Mat kernel, Point anchor, double delta) 它将图像与内核进行卷积。 |
5 |
GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX) 它使用高斯滤波器模糊图像。 |
6 |
integral(Mat src, Mat sum) 它计算图像的积分。 |
示例
以下示例演示了如何使用 Imgproc 类将 Prewitt 运算符应用于灰度图像。
import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class convolution { public static void main( String[] args ) { try { int kernelSize = 9; System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread("grayscale.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(),source.cols(),source.type()); Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) { { put(0,0,-1); put(0,1,0); put(0,2,1); put(1,0-1); put(1,1,0); put(1,2,1); put(2,0,-1); put(2,1,0); put(2,2,1); } }; Imgproc.filter2D(source, destination, -1, kernel); Highgui.imwrite("output.jpg", destination); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
输出
执行给定的代码时,将看到以下输出 −
原始图像

此原始图像与垂直边缘的 Prewitt 算子进行卷积,如下所示 −
垂直方向
-1 | 0 | 1 |
-1 | 0 | 1 |
-1 | 0 | 1 |
卷积图像(垂直方向)

此原始图像还与水平边缘的 Prewitt 算子进行了卷积,如下所示 −
水平方向
-1 | -1 | -1 |
0 | 0 | 0 |
1 | 1 | 1 |
卷积图像(水平方向)
