Goal
在本教程中,您将学习如何:
使用 OpenCV 函数 cv::pointPolygonTest
Theory
Code
本教程代码如下所示。 你也可以从这里下载https://github.com/opencv/opencv/tree/4.x/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp
/**
* @function pointPolygonTest_demo.cpp
* @brief 使用 pointPolygonTest 函数的演示代码...相当简单
* @author OpenCV team
*/
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
/**
* @function main
*/
int main( void )
{
/// 创建图像
const int r = 100;
Mat src = Mat::zeros( Size( 4*r, 4*r ), CV_8U );
/// 创建一系列点以制作轮廓 Create a sequence of points to make a contour
vector<Point2f> vert(6);
vert[0] = Point( 3*r/2, static_cast<int>(1.34*r) );
vert[1] = Point( 1*r, 2*r );
vert[2] = Point( 3*r/2, static_cast<int>(2.866*r) );
vert[3] = Point( 5*r/2, static_cast<int>(2.866*r) );
vert[4] = Point( 3*r, 2*r );
vert[5] = Point( 5*r/2, static_cast<int>(1.34*r) );
/// 在 src 中绘制
for( int i = 0; i < 6; i++ )
{
line( src, vert[i], vert[(i+1)%6], Scalar( 255 ), 3 );//封闭多边形
}
/// 获取轮廓 Get the contours
vector<vector<Point> > contours;
findContours( src, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);//预先知道只有一个轮廓
///计算到轮廓的距离 Calculate the distances to the contour
Mat raw_dist( src.size(), CV_32F );
for( int i = 0; i < src.rows; i++ )
{
for( int j = 0; j < src.cols; j++ )
{ //像素值 为 点到轮廓的距离 。 pointPolygonTest 检测点是否在轮廓内
raw_dist.at<float>(i,j) = (float)pointPolygonTest( contours[0], Point2f((float)j, (float)i), true );
}
}
double minVal, maxVal;
Point maxDistPt; // 内接圆心 inscribed circle center
minMaxLoc(raw_dist, &minVal, &maxVal, NULL, &maxDistPt);//找到图像的最小最大像素值 以及最大像素值的点
minVal = abs(minVal);//取绝对值。 轮廓外最大距离
maxVal = abs(maxVal);//轮廓内最大距离
///以图形方式描述距离 Depicting the distances graphically
Mat drawing = Mat::zeros( src.size(), CV_8UC3 );//三通道黑色背景图
for( int i = 0; i < src.rows; i++ )
{
for( int j = 0; j < src.cols; j++ )
{
if( raw_dist.at<float>(i,j) < 0 )//轮廓外的点 第i行第j列灰度图 像素值为负
{ //B通道 (255-距离)*255/最大距离
drawing.at<Vec3b>(i,j)[0] = (uchar)(255 - abs(raw_dist.at<float>(i,j)) * 255 / minVal);
}
else if( raw_dist.at<float>(i,j) > 0 )//轮廓内的点
{ //R通道 (255-距离)*255/最大距离
drawing.at<Vec3b>(i,j)[2] = (uchar)(255 - raw_dist.at<float>(i,j) * 255 / maxVal);
}
else//轮廓上的点 白色
{
drawing.at<Vec3b>(i,j)[0] = 255;
drawing.at<Vec3b>(i,j)[1] = 255;
drawing.at<Vec3b>(i,j)[2] = 255;
}
}
}
circle(drawing, maxDistPt, (int)maxVal, Scalar(255,255,255));//绘制 白色的圆
/// 显示结果
imshow( "Source", src );
imshow( "Distance and inscribed circle", drawing );
waitKey();
return 0;
}
Explanation
Result
参考:
opencv函数
pointPolygonTest: OpenCV学习三十三:pointPolygonTest 检测点是否在轮廓内_Thomas会写字的博客-CSDN博客_pointpolygontest
C++: double pointPolygonTest(InputArray contour, Point2f pt, bool measureDist)
用于测试一个点是否在多边形中
当measureDist设置为true时,返回实际距离值。若返回值为正,表示点在多边形内部,返回值为负,表示在多边形外部,返回值为0,表示在多边形上。
当measureDist设置为false时,返回 -1、0、1三个固定值。若返回值为+1,表示点在多边形内部,返回值为-1,表示在多边形外部,返回值为0,表示在多边形上。