Opencv-distance-transformation

提供:Dev Guides
移動先:案内検索

OpenCV-距離変換

  • 距離変換*演算子は通常、バイナリイメージを入力として受け取ります。 この操作では、前景領域内のポイントのグレーレベルの強度を変更して、それぞれの距離を最も近い0の値(境界)から離します。

メソッド* distanceTransform()*を使用して、OpenCVで距離変換を適用できます。 このメソッドの構文は次のとおりです。

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 が次のようになっていると仮定します。

距離変換入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

距離変換出力

距離変換操作のタイプ

前の例で示した距離操作タイプ DIST_C に加えて、OpenCVは他のさまざまなタイプの距離変換操作に対応しています。 これらのタイプはすべて、Imgprocクラスの事前定義された静的フィールド(固定値)によって表されます。

それぞれの事前定義値を* distanceTransform()メソッドの *distanceType という名前のパラメーターに渡すことで、必要な距離変換操作のタイプを選択できます。

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

以下は、さまざまなタイプの distanceTransform 操作とそれぞれの出力を表す値です。

Operation and Description Output
DIST_C DIST_C
DIST_L1 DIST_L1
DIST_L2 DIST_L2
DIST_LABEL_PIXEL DIST_LABEL_PIXEL
DIST_MASK_3 DIST_MASK_3