Java 數字影像處理 - Sobel 運算元



Sobel 運算元與 Prewitt 運算元非常相似。它也是一種導數掩碼,用於邊緣檢測。Sobel 運算元用於檢測影像中的兩種邊緣:垂直方向邊緣和水平方向邊緣。

我們將使用 **OpenCV** 函式 **filter2D** 將 Sobel 運算元應用於影像。它可以在 **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 類將 Sobel 運算元應用於灰度影像。

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-2);
               put(1,1,0);
               put(1,2,2);

               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 Sobel operator Tutorial

此原始影像與垂直邊緣的 Sobel 運算元進行卷積,如下所示:

垂直方向

-1 0 1
-2 0 2
-1 0 1

卷積影像(垂直方向)

Applying Sobel operator Tutorial

此原始影像與水平邊緣的 Sobel 運算元進行卷積,如下所示:

水平方向

-1 -2 -1
0 0 0
1 2 1

卷積影像(水平方向)

Applying Sobel operator Tutorial
廣告

© . All rights reserved.