距离变换操作通常将二值图像作为输入。 在这个操作中,前景区域内的点的灰度强度被改变,以距离它们各自距最近的0值(边界)的距离。
可以使用distanceTransform()
方法在OpenCV中应用距离转换。以下是此方法的语法。
distanceTransform(src, dst, distanceType, maskSize)
该方法接受以下参数 -
Mat
类的对象。Mat
类的对象。示例
以下程序演示如何对给定图像执行距离转换操作。
package com.zyiz.transformation; 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 ="F:/worksp/opencv/images/sample3.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(src, dst, Imgproc.DIST_C, 3); // Writing the image Imgcodecs.imwrite("F:/worksp/opencv/images/sample3distnceTransform.jpg", dst); System.out.println("Image Processed"); } }
假定以下是上述程序中指定的输入图像sample3.jpg
。
执行上面示例代码,得到以下结果 -