OpenCV - 膨脹



腐蝕和膨脹是兩種形態學操作。顧名思義,形態學操作是一組根據影像形狀處理影像的操作。

基於給定的輸入影像,會開發一個“結構元素”。這可以透過兩種過程中的任何一種來完成。這些過程旨在去除噪聲並消除瑕疵,使影像更清晰。

膨脹

此過程遵循使用特定形狀(例如正方形或圓形)的某個核心進行卷積。此核心具有一個錨點,表示其中心。

此核心與影像重疊以計算最大畫素值。計算後,影像將替換為中心處的錨點。透過此過程,明亮區域的面積會增大,因此影像尺寸會增大。

例如,白色或亮色陰影中物體的尺寸會增大,而黑色或暗色陰影中物體的尺寸會減小。

您可以使用imgproc類的dilate()方法對影像執行膨脹操作。以下是此方法的語法。

dilate(src, dst, kernel)

此方法接受以下引數:

  • src - 表示此操作的源(輸入影像)的Mat物件。

  • dst - 表示此操作的目標(輸出影像)的Mat物件。

  • kernel - 表示核心的Mat物件。

示例

您可以使用getStructuringElement()方法準備核心矩陣。此方法接受一個表示morph_rect型別的整數和一個Size型別的物件。

Imgproc.getStructuringElement(int shape, Size ksize);

以下程式演示瞭如何在給定影像上執行膨脹操作。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DilateTest {
   public static void main( String[] args ) {
      // Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      // Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();

      // Preparing the kernel matrix object 
      Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, 
         new  Size((2*2) + 1, (2*2)+1));

      // Applying dilate on the Image
      Imgproc.dilate(src, dst, kernel);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap10/Dilation.jpg", dst);

      System.out.println("Image Processed");
   } 
}

輸入

假設以下是由上述程式指定的輸入影像sample.jpg

Sample Image

輸出

執行程式後,您將獲得以下輸出:

Image Processed

如果開啟指定的路徑,您可以觀察到輸出影像如下:

Dilation
廣告

© . All rights reserved.