【问题标题】:OpenCV sort points stored in Point2f vectorOpenCV 排序点存储在 Point2f 向量中
【发布时间】:2015-06-15 04:35:06
【问题描述】:

我正在尝试使用the following 算法对minAreaRect 返回的结果进行排序:

这是我现在的代码:

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?!? */
}

但它不起作用,没有编译错误,但是点没有排序。我认为数据类型有问题。

【问题讨论】:

  • 我认为这个算法不会对你的数据进行排序!
  • 我更新了我的问题,在那里你可以看到原始算法。

标签: c++ opencv


【解决方案1】:

您提供的算法仅在 4 个点属于平行于 x-y 轴的矩形时才有效。此外,您尝试返回结果的方式也将无法正常工作。尝试将sorted 数组复制回unsorted。像这样for ( int i=0;i&lt;4;++i ) unsorted[i] = sorted[i];

但是你可以使用某些方法

#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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多