我正在尝试使用 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?!? */
}
但是它不起作用,没有编译错误,但是点没有排序。我认为数据类型有问题。
最佳答案
您提供的算法仅在 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/