c++ - OpenCV 对存储在 Point2f vector 中的点进行排序

标签 c++ opencv

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

这是我现在的代码:

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

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

最佳答案

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

关于c++ - OpenCV 对存储在 Point2f vector 中的点进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30833039/

相关文章:

c++ - 您的计算机缺少 tbb.dll

C++ 控制台保存并加载保存的 "games"

c++ - 网格引擎集群+OpenCV : strange behaviour

python - 如何将二值图像表示为图形,轴为高度和宽度尺寸,数据为像素

c++ - 使用抗锯齿时箭头尖端的像素丢失

c++ - 使用 Nvidia Optix 和开放 Assets 导入库 (assimp) 进行光线追踪 - 渲染多个网格

c++ - 在 C++ 中应该如何声明类字段?

c++ - 全局智能指针未正确清理

opencv - 将图像转换为灰度的影响

android - 在Android中使用OpenCV录制视频