简体   繁体   中英

OpenCV sort points stored in Point2f vector

I am trying to sort the result returned by minAreaRect using the following algorithm:

Here's my code for now:

void sortPoints(Point2f* unsorted) {

    Point2f sorted[4];

    for (int i = 0; i < 4; i++) sorted[i] = Point(0, 0);

    float middleX = (unsorted[0].x + unsorted[1].x + unsorted[2].x + unsorted[3].x) / 4;
    float middleY = (unsorted[0].y + unsorted[1].y + unsorted[2].y + unsorted[3].y) / 4;

    for (int i = 0; i < 4; i++) {
        if (unsorted[i].x < middleX && unsorted[i].y < middleY) sorted[0] = unsorted[i];
        if (unsorted[i].x > middleX && unsorted[i].y < middleY) sorted[1] = unsorted[i];
        if (unsorted[i].x < middleX && unsorted[i].y > middleY) sorted[2] = unsorted[i];
        if (unsorted[i].x > middleX && unsorted[i].y > middleY) sorted[3] = unsorted[i];
    }

    unsorted = sorted;

}

...

vector<RotatedRect> minRect( contours.size() );

for( int i = 0; i < contours.size(); i++ ) { 
     minRect[i] = minAreaRect( Mat(contours[i]) );
}

Point2f rect_points[4]; 

for( int i = 0; i < contours.size(); i++ ) {
     minRect[i].points( rect_points );
     sortPoints( rect_points ); /* ...they are not sorted after calling sortPoints?!? */
}

But it's not working, no compile error, but the points are not sorted. I think there's something wrong with data types.

The algorithm you provided only works if the 4 points belong to a rectangle parallel to xy axis. Also the way you try to return result will not work properly. Try copying the sorted array back to unsorted . like this for ( int i=0;i<4;++i ) unsorted[i] = sorted[i];

But there is certain way you can use

#include <algorithm>
struct str{
    bool operator() ( Point2f a, Point2f b ){
        if ( a.y != b.y ) 
            return a.y < b.y;
        return a.x <= b.x ;
    }
} comp;

int main()
{
Point2f v[4];
v[0] = Point2f(0,1);
v[1] = Point2f(-1,1);
v[2] = Point2f(2,1);
v[3] = Point2f(4,1);

sort(v,v+4,comp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM