问题
I extracted 110 coordinates from contours of a 10x11 LED-Array using C++ and OpenCV and stored them in a vector. Now I want to sort them from top left to bottom right to detect if a LED in a certain row and column is on. I presorted the coordinates by y-position to make sure that the first 10 coordinates in the vector representing the first LED row in my Image.
vector<Point2f> centers;
bool compareY(Point2f p1, Point2f p2){
if(p1.y < p2.y) return true;
if(p1.y > p2.y) return false;
}
sort(centers.begin(), centers.end(), compareY);
Now I have to sort them by x-position. The problem is that the x-position from the first LED in row two or any other row can be a bit smaller then the first LED in row one. Due to that fact they have to be sorted from centers[0] to centers[9], centers[10] to centers[20]... row by row. Has anybody an idea how to do that?
Thanks in advance!
EDIT: Managed to sort the points but my algorithm based on contour detection is not robust enough to detect all LEDs. Has anyone an idea for a robust method to detect them?
回答1:
If you want to perform a lexicographical sorting by Y coordinate and then X coordinate, you just have to provide a suitable comparison function that really implements a strict weak ordering using. For example
#include <tuple>
bool compareYX(const Point2f& p1, const Point2f& p2)
{
return std::tie(p1.y, p1.x) < std::tie(p2.y, p2.x);
}
You can also implement the lexicographical comparison manually, but this is quite error-prone.
来源:https://stackoverflow.com/questions/24528285/sort-coordinates-from-top-left-to-bottom-right