本章内容:
1. 轮廓查找
2. 绘制轮廓
3. 点多边形测试
输出结果
源码
#include <ostream>
#include <opencv.hpp>
#include <math.h>int main(int argc, char *argv[])
{
/*
本章内容:
1. 轮廓查找
2. 绘制轮廓
3. 点多边形测试
*/
cv::String fileName = "/home/wang/dev/Image/QT.jpg";
cv::String fileName1 = "/home/wang/dev/Image/hei.png";
cv::Mat src = cv::imread(fileName);
cv::Mat src1 = cv::imread(fileName1);
if(src.data == NULL){
printf("图像读入失败\n");
return -1;
}
cv::imshow("src",src);
cv::Mat dstCany;
cv::Mat gray;
cv::cvtColor(src,gray,cv::COLOR_BGR2GRAY);
cv::Canny(gray,dstCany,50,150);
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(dstCany,contours,hierarchy,cv::RETR_TREE,cv::CHAIN_APPROX_SIMPLE,cv::Point(0,0));
cv::RNG rng(1234);
cv::Mat dst1(src.size(),CV_32FC1);
// 点多边形测试
for(int i=0;i<dst1.rows;i++){
for(int j=0; j<dst1.cols;j++){
cv::Point2f pt(i,j);
double dist = cv::pointPolygonTest(contours[0],pt,true);
dst1.at<float>(i,j) =dist;
}
}
double minVal;
double maxVal;
cv::Mat dst(src.size(),CV_8UC3);
cv::minMaxIdx(dst1,&minVal,&maxVal);
for(int i=0;i<dst.rows;i++){
for(int j=0; j<dst.cols;j++){
float tem = dst1.at<float>(i,j);
if(tem > 0) dst.at<cv::Vec3b>(i,j)[2] = tem / maxVal*255 ;
else dst.at<cv::Vec3b>(i,j) = tem / minVal*255;}
}
//绘制曲线
cv::Scalar color = cv::Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255));
cv::drawContours(dst,contours,0,color,4);
cv::imshow("dst",dst);
cv::waitKey(0);
return 1;
}