OpenCV - 腐蝕



腐蝕與膨脹非常相似,但這裡計算的畫素值是最小值,而不是膨脹中的最大值。影像在錨點下用該最小畫素值替換。

透過此過程,暗區域的面積會增大,而亮區域的面積會減小。例如,深色陰影或黑色陰影中物體的尺寸會增加,而在白色陰影或亮色陰影中則會減小。

示例

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

erode(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 ErodeTest {
   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 erode on the Image
      Imgproc.erode(src, dst, kernel);

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

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

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

Sample Image

輸出

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

Image Loaded

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

Erosion
廣告