Java 數字影像處理 - 腐蝕和膨脹



在本章中,我們將學習應用兩個非常常見的形態學運算子:膨脹和腐蝕。

我們使用 **OpenCV** 函式 **erode** 和 **dilate**。它們可以在 **Imgproc** 包中找到。其語法如下所示:

Imgproc.erode(source, destination, element);
Imgproc.dilate(source, destination, element);				

引數描述如下:

序號 引數及描述
1

source

源影像。

2

destination

目標影像。

3

element

用於腐蝕和膨脹的結構元素,如果 element=Mat(),則使用 3 x 3 的矩形結構元素。

除了 erode() 和 dilate() 方法外,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 類對影像執行腐蝕和膨脹操作:

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 main {
   public static void main( String[] args ) {
   
      try{	
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         Mat source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         destination = source;

         int erosion_size = 5;
         int dilation_size = 5;
         
         Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new  Size(2*erosion_size + 1, 2*erosion_size+1));
         Imgproc.erode(source, destination, element);
         Highgui.imwrite("erosion.jpg", destination);

         source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         
         destination = source;
         
         Mat element1 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new  Size(2*dilation_size + 1, 2*dilation_size+1));
         Imgproc.dilate(source, destination, element1);
         Highgui.imwrite("dilation.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("error:" + e.getMessage());
      } 
   }
}

輸出

執行給定程式碼後,將看到以下輸出:

原始影像

Eroding and Dilating Tutorial

在上面的原始影像上,執行了一些腐蝕和膨脹操作,並在下面的輸出中顯示:

腐蝕

Eroding and Dilating Tutorial

膨脹

Eroding and Dilating Tutorial
廣告

© . All rights reserved.