本片博客转载自(感谢博主分享):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;
}
效果: