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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我就是不按套路出牌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值