判斷一個點是否在RotatedRect中


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/






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM