OpenCV Java 检测点是否在轮廓内

package com.opencv;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;

public class OpenCvMain {
	
	//静态代码块加载动态链接库
	static {
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	}

	public static void main(String[] args) {
		
		int r = 100;
		Mat src = Mat.zeros( new Size( 4*r, 4*r ), CvType.CV_8UC1 );
		
		List<Point> vert = new ArrayList<Point>();
		vert.add(new Point(3*r/2, 1.34*r));
		vert.add(new Point(1*r, 2*r));
		vert.add(new Point(3*r/2, 2.866*r));
		vert.add(new Point(5*r/2, 2.866*r));
		vert.add(new Point(3*r, 2*r));
		vert.add(new Point(5*r/2, 1.34*r));
		for(int i=0;i<vert.size();i++) {
			Imgproc.line(src, vert.get(i), vert.get((i+1)%6), new Scalar(255),3,8);
		}
		
		/*
		 * 查找二进制图像中的轮廓
		 * https://blog.csdn.net/ren365880/article/details/103970023
		 */
		List<MatOfPoint> list = new ArrayList<MatOfPoint>();
		Mat hierarchy = new Mat();
		Imgproc.findContours(src, list, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE,new Point(0, 0));

		
		Mat rawDist = new Mat( src.size(), CvType.CV_32FC1 );
		for( int j = 0; j < src.rows(); j++ ){ 
			for( int i = 0; i < src.cols(); i++ ){
				MatOfPoint2f matOfPoint2fnew = new MatOfPoint2f();
				matOfPoint2fnew.fromList(list.get(0).toList());
				/*
				 * 执行轮廓点测试。 该函数确定该点是在轮廓内部,外部还是在边缘上(或与顶点重合)。 它分别返回正(内部),负(外部)或零(边缘)值。
				 * 当measureDist = false时,返回值分别为+ 1,-1和0。 否则,返回值是该点与最近的轮廓边之间的有符号距离。
				 * 参见下面的函数示例输出,其中针对轮廓测试每个图像像素:
				 * @param contour 输入轮廓。
				 * @param pt 测试点。
				 * @param measureDist如果为true,则该函数估计从点到最近的轮廓边的有符号距离。 否则,该功能仅检查该点是否在轮廓内。
				 */
				rawDist.put(j,i,Imgproc.pointPolygonTest(matOfPoint2fnew , new Point(i,j), true ));
			}
	     }
		

		MinMaxLocResult result = Core.minMaxLoc(rawDist);
		double minVal = Math.abs(result.minVal);
		double maxVal = Math.abs(result.maxVal);
		Mat drawing = Mat.zeros( src.size(), CvType.CV_8UC3 );
		
		for( int j = 0; j < src.rows(); j++ ){
			for( int i = 0; i < src.cols(); i++ ){
	            if( rawDist.get(j, i)[0] < 0 ){ //外部
	            	drawing.put(j, i,255-Math.abs(rawDist.get(j, i)[0])*255/minVal,0,0);
	            }else if( rawDist.get(j, i)[0] > 0 ){ //内部
	            	drawing.put(j, i,0,0,255-Math.abs(rawDist.get(j, i)[0])*255/maxVal);
	            }else{ //边缘
	            	drawing.put(j, i,255,255,255);
	            }
			}
		}
		
		HighGui.imshow("图片", drawing);
		HighGui.waitKey();
	}
}

OpenCV Java 检测点是否在轮廓内_第1张图片

你可能感兴趣的:(OpenCV4.2,for,Java,java)