Bootstrap

Opencv C++ 检测点在轮廓的位置

          pointPolygonTest用于判断一个点是否在一个多边形内。函数会返回一个double uuuuu  类型的值。

  • 如果点在多边形内部,返回正数;
  • 如果点在多边形外部,返回负数;
  • 如果点在多边形的边缘上,返回零;

 检测点在轮廓的位置API:

double pointPolygonTest(InputArray contour,
                        Point2f pt,
                        bool measureDist
)

参数解析:

//InputArray contour:输入的轮廓;
//Point2f pt:输入被检测的点;
//bool measureDist:如果为true,该返回值为点到变的最近距离;当为false,则返回-1,+1,0;

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace cv;
using namespace std;

int main(int argc,char*argv)
{
	Mat src = Mat::zeros(Size(512, 512), CV_8UC1);

	vector<Point2f>Poly = { Point2f(50, 300), Point2f(100, 200),Point2f(200, 200),Point2f(250, 300), Point2f(200, 400), Point2f(100, 400) };
	for (size_t i = 0; i < 5; i++)
	{
		line(src, Poly[i], Poly[i + 1], Scalar(255), 1, 8, 0);
	}
	line(src, Poly[5], Poly[0], Scalar(255), 1);
	imshow("src",src);

	vector<vector<Point>>contours;
	findContours(src, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);

	Mat drawImg=Mat::zeros(src.size(),CV_32FC3);
	drawContours(drawImg, contours, -1, Scalar(0, 0, 255));
	imshow("drawImg", drawImg);

	Mat resultImg = Mat::zeros(src.size(), CV_32FC1);
	for (int row = 0; row < src.rows; row++)
	{
		for (int col = 0; col < src.cols; col++)
		{
			resultImg.at<float>(col,row) = (float)pointPolygonTest(contours[0], Point2f((float)row, (float)col), true);
		}
	}
	imshow("resultImg", resultImg);
	
	Mat dst = Mat::zeros(src.size(), CV_8UC3);
	for (int row = 0; row < src.rows; row++)
	{
		for (int col = 0; col < src.cols; col++)
		{
			float distance = resultImg.at<float>(col, row);
			if (distance>0.0)
			{
				dst.at<Vec3b>(col, row)[0] = distance;
			}
			else if (distance<0.0)
			{
				dst.at<Vec3b>(col, row)[1] = saturate_cast<uchar>(abs(distance));
				dst.at<Vec3b>(col, row)[2] = saturate_cast<uchar>(abs(distance));
			}
			else
			{
				dst.at<Vec3b>(col, row)[2] = 255;
			}
		}
	}
	imshow("dst", dst);

	waitKey();
	return 0;
}

;