Java 数字图像处理 - Prewitt 算子



Prewitt 算子用于图像边缘检测。它检测两种类型的边缘:垂直边缘和水平边缘。

我们使用OpenCV 函数filter2D 将 Prewitt 算子应用于图像。它可以在Imgproc 包中找到。其语法如下:

filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );

函数参数描述如下:

序号 参数及描述
1

src

源图像。

2

dst

目标图像。

3

depth

dst 的深度。负值(例如 -1)表示深度与源图像相同。

4

kernel

扫描图像的核。

5

anchor

锚点相对于其核的位置。默认情况下,位置 Point(-1, -1) 表示中心。

6

delta

在卷积过程中添加到每个像素的值。默认为 0。

7

BORDER_DEFAULT

我们使用默认值。

除了 filter2D 方法外,Imgproc 类还提供了其他方法。简要描述如下:

序号 方法及描述
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, int depth, 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());
      }
   }
}

输出

执行给定代码后,将看到以下输出:

原始图像

Applying Prewitt operator Tutorial

此原始图像与如下所示的垂直边缘 Prewitt 算子进行卷积:

垂直方向

-1 0 1
-1 0 1
-1 0 1

卷积图像(垂直方向)

Applying Prewitt operator Tutorial

此原始图像还与如下所示的水平边缘 Prewitt 算子进行了卷积:

水平方向

-1 -1 -1
0 0 0
1 1 1

卷积图像(水平方向)

Applying Prewitt operator Tutorial
广告