在opencv中对有界矩形进行排序

时间:2015-02-16 15:35:08

标签: c++ opencv

我在矢量中有一组有界矩形为Rect。

vector(Rect) boundRect( contours.size() );

我想对这些矩形进行排序,如下图所示

image http://img42.com/liVFt

我已经尝试过使用下面的方法了,但是我没有像我发布的图片那样收到订单。

stable_sort( boundRect.begin(), boundRect.end(), compareX_rect );
stable_sort( boundRect.begin(), boundRect.end(), compareY_rect );

bool compareX_rect(const Rect & a, const Rect &b) {
    return a.x >= b.x;
}
bool compareY_rect(const Rect & a, const Rect &b) {
    return a.y >= b.y;
}

有人可以帮我这个吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

组合成单一排序,其中排序将首先比较y值,然后是x值:

编辑:修正了在编码地测试的排序:

bool compareFn(Rectangle* l, Rectangle* r) {
    if(l->y == r->y) return l->x < r->x;
    return (l->y < r->y);
}

为了减少噪音(取决于涉及多少噪音),您可以执行底部或圆形功能,或计算y值所属的“单元格”。只需增加单元尺寸,直到它克服噪音:

float cellSize = 20.0f;
bool compareFn(Rectangle* l, Rectangle* r) {
    float lCell = floorf(l->y / cellSize);
    float rCell = floorf(r->y / cellSize);
    if(lCell == rCell) return l->x < r->x;
    return (lCell < rCell);
}

这是测试它的程序(没有降噪):

#include <iostream>
#include <vector>
#include <algorithm>    // std::sort

using namespace std;

struct Rectangle {
    float x;
    float y; 
    float width; 
    float height;

    Rectangle(float x_, float y_, float w_, float h_)
    : x(x_)
    , y(y_)
    , width(w_)
    , height(h_)
    {}

};

bool compareFn(Rectangle* l, Rectangle* r) {
    if(l->y == r->y) return l->x < r->x;
    return (l->y < r->y);
}

int main()
{
   vector<Rectangle*> rectangles;
   for(int x=0; x<10; ++x) {
       for(int y=0; y<10; ++y) {
           Rectangle* rect = new Rectangle((9 - x) * 50, (9-y) * 50, 50, 50);
           rectangles.push_back(rect);
       }
   }

   printf("SORTING\n");
   sort(rectangles.begin(), rectangles.end(), compareFn);

   printf("RESULTS\n");
   for(vector<Rectangle*>::iterator it=rectangles.begin(), end=rectangles.end(); it!=end; ++it) {
       Rectangle* rect = *it;
       printf("[%f, %f, %f, %f]\n", rect->x, rect->y, rect->width, rect->height);
   }

   return 0;
}