天天看點

C++ OpenCV點是否在給定的輪廓中來判斷

尋找輪廓的方法在前面和章裡面都經常用到了,如果我們判斷一個點是否在輪廓裡面的話,OpenCV有這個函數來進行判斷。

相關API

double pointPolygonTest(InputArray contour, Point2f pt, bool measureDist)

  • contour ---輸入輪廓
  • pt ---針對輪廓需要測試的點
  • measure_dist ---如果非0,函數将估算點到輪廓最近邊的距離。

用于測試一個點是否在多邊形中

當measureDist設定為true時,若傳回值為正,表示點在多邊形内部,傳回值為負,表示在多邊形外部,傳回值為0,表示在多邊形上。

當measureDist設定為false時,若傳回值為+1,表示點在多邊形内部,傳回值為-1,表示在多邊形外部,傳回值為0,表示在多邊形上。

檢測點的核心代碼

代碼段一

/// 得到輪廓

std::vector<std::vector<cv::Point> > contours;

std::vector<cv::Vec4i> hierarchy;

cv::Mat src; //src為圖像

//contours為函數findContours計算得到的輪廓點分布值

cv::findContours( src_copy, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);

// 計算到輪廓的距離

cv::Mat raw_dist( src.size(), CV_32FC1 );

for( int j = 0; j < src.rows; j++ ){

for( int i = 0; i < src.cols; i++ ){

raw_dist.at<float>(j,i) = cv::pointPolygonTest( contours[0], Point2f(i,j), true );

}

代碼段二

/// 查找輪廓

std::vector<std::vector<cv::Point> > contours;

cv::Mat src; //src為輸入圖像

cv::findContours( src, contours, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,Point(0,0));

//判斷p1(x,y)是否在輪廓内

cv::Point p1(x,y);

if (pointPolygonTest(Contours[j],cv::Point(x1,y1),false) == 1)

{

cout<<p1<<"在輪廓内"<<endl;

}

-END-