OpenCV3历程(10)——轮廓特征应用:计算点与轮廓距离

本片博客转载自(感谢博主分享):https://blog.csdn.net/abcvincent/article/details/79275615

opencv实现了Contours与point的距离关系的计算使用起来很方便,不用自己再进行坐标转换计算了;示例代码如下:

(对原先博主的代码进行了略微的修改)

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

using namespace cv;
using namespace std;

int main()
{
	//1.查找轮廓的预处理
	Mat srcImage = imread("./image/点.jpg", 1);
	Mat copyImg = srcImage.clone();
	cvtColor(srcImage, srcImage, CV_BGR2GRAY);
	threshold(srcImage, srcImage, 100, 255, CV_THRESH_BINARY);
	imshow("thresh", srcImage);
	//2.查找轮廓
	vector<vector<Point>> contours;
	findContours(srcImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//最外层轮廓
	drawContours(copyImg, contours, -1, Scalar(0, 255, 0), 2, 8);
	//3.计算点到轮廓的距离与位置关系
	Point2f point1(230, 200);
	circle(copyImg, point1, 3, Scalar(255, 0, 0), -1, 8);
	//true表示点到轮廓的距离
	double a0 = pointPolygonTest(contours[0], point1, true);
	//false表示计算点与轮廓的位置关系-1表示外部,0在轮廓上,1在轮廓内
	double b0 = pointPolygonTest(contours[0], point1, false);
	cout << "a0=" << a0 << endl;
	cout << "b0=" << b0 << endl;

	Point2f point2(150, 200);
	circle(copyImg, point2, 3, Scalar(0, 0, 255), -1, 8);
	double a1 = pointPolygonTest(contours[0], point2, true);
	double b1 = pointPolygonTest(contours[0], point2, false);
	cout << "a1=" << a1 << endl;
	cout << "b1=" << b1 << endl;

	//添加文字(将double类型转换为char)
	ostringstream oss1;
	oss1 << a0;
	char fileName1[50];
	memset(fileName1, 0, 50);
	//先转化为流,再转换为string, 然后再转换为char
	strcat(fileName1, (oss1.str()).c_str());
	putText(copyImg, fileName1, Point(30, 30), CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(255, 0, 0), 1, 8);

	//添加文字
	ostringstream oss2;
	oss2 << b0;
	char fileName2[50];
	memset(fileName2, 0, 50);
	//先转化为流,再转换为string, 然后再转换为char
	strcat(fileName2, (oss2.str()).c_str());
	putText(copyImg, fileName2, Point(30, 30*2), CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(255, 0, 0), 1, 8);

	//添加文字
	ostringstream oss3;
	oss3 << a1;
	char fileName3[50];
	memset(fileName3, 0, 50);
	//先转化为流,再转换为string, 然后再转换为char
	strcat(fileName3, (oss3.str()).c_str());
	putText(copyImg, fileName3, Point(30, 30*3), CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(0, 0, 255), 1, 8);

	//添加文字
	ostringstream oss4;
	oss4 << b1;
	char fileName4[50];
	memset(fileName4, 0, 50);
	//先转化为流,再转换为string, 然后再转换为char
	strcat(fileName4, (oss4.str()).c_str());
	putText(copyImg, fileName4, Point(30, 30*4), CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(0, 0, 255), 1, 8);

	imshow("contours", copyImg);
	waitKey(0);
	return 0;
}

 效果:

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值