OpenCV - 距離變換



距離變換操作通常以二值影像作為輸入。在此操作中,前景區域內點的灰度強度會更改為它們各自到最近的 0 值(邊界)的距離。

您可以使用 OpenCV 中的distanceTransform()方法應用距離變換。以下是此方法的語法。

distanceTransform(src, dst, distanceType, maskSize)

此方法接受以下引數 -

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

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

  • distanceType - 表示要應用的距離變換型別的整數型別變數。

  • maskSize - 表示要使用的掩碼大小的整數型別變數。

示例

以下程式演示瞭如何在給定影像上執行距離變換操作。

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

public class DistanceTransform {
   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 ="E:/OpenCV/chap19/input.jpg";
      Mat src = Imgcodecs.imread(file,0);

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

      // Converting the grayscale image to binary image
      Imgproc.threshold(src, binary, 100, 255, Imgproc.THRESH_BINARY);

      // Applying distance transform
      Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);

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

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

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

Distance Transformation Input

輸出

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

Image Processed

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

Distance Transformation Output

距離變換操作型別

除了在前面的示例中演示的距離操作型別DIST_C之外,OpenCV 還提供各種其他型別的距離變換操作。所有這些型別都由 Imgproc 類的預定義靜態欄位(固定值)表示。

您可以透過將其相應的預定義值傳遞給distanceTransform()方法的distanceType引數來選擇所需的距離變換操作型別。

// Applying distance transform 
Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);

以下是表示各種distanceTransform操作型別及其相應輸出的值。

操作和描述 輸出
DIST_C DIST_C
DIST_L1 DIST_L1
DIST_L2 DIST_L2
DIST_LABEL_PIXEL DIST_LABEL_PIXEL
DIST_MASK_3 DIST_MASK_3
廣告