判斷一個點是否在RotatedRect中
阿新 • • 發佈:2018-12-09
openCV函式pointPolygonTest():
C++: double pointPolygonTest(InputArray contour, Point2f pt, bool measureDist)
用於判斷一個點是否在輪廓中
當measureDist設定為true時,若返回值為正,表示點在輪廓內部,返回值為負,表示在輪廓外部,返回值為0,表示在輪廓上。
當measureDist設定為false時,若返回值為+1,表示點在輪廓內部,返回值為-1,表示在輪廓外部,返回值為0,表示在輪廓上。
例:
……/// 查詢輪廓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; } ……
但是這個函式是用來處理“輪廓”,也就是點的集合的;對於這裡RotatedRect,它本身只是一個OpenCV的資料結構,所以我們如果想使用pointPolygonTest,就需要首先將RotatedRect轉換為輪廓。對於RotatedRect,其實轉換很簡單,直接將它的四個角的座標塞到一個Vector<point>裡面就可
以,當然了,對於其它複雜輪廓來說,可能會需要更多操作。
那麼,最後合成的程式為:
bool DoesRectangleContainPoint(RotatedRect rectangle, Point2f point) { //Get the corner points. Point2f corners[4]; rectangle.points(corners); //Convert the point array to a vector. //https://stackoverflow.com/a/8777619/1997617 Point2f* lastItemPointer = (corners + sizeof corners / sizeof corners[0]); vector<Point2f> contour(corners, lastItemPointer); //Check if the point is within the rectangle. double indicator = pointPolygonTest(contour, point, false); bool rectangleContainsPoint = (indicator >= 0); return rectangleContainsPoint; }
需要注意的是,在這裡indicator >= 0,如果你是判斷是否在輪廓上,要修改為indicator == 0
參考:http://answers.opencv.org/question/30330/check-if-a-point-is-inside-a-rotatedrect/