Sorting 2nd array of points to define four corners
2 answers
Perhaps you can use cv::approxPoly()
to find the corners of your set of 2D points. Then you can sort the points in any order you want, like this:
//Sorts a vector of 4 points into top left, top right, bottomleft, bottomright
vector<Point> sortPoints(vector<Point> unsorted) {
vector<Point> sorted;
for (int i = 0; i < 4; i++)sorted.push_back(Point(0, 0));
int middleX = (unsorted[0].x + unsorted[1].x + unsorted[2].x + unsorted[3].x) / 4;
int middleY = (unsorted[0].y + unsorted[1].y + unsorted[2].y + unsorted[3].y) / 4;
for (int i = 0; i < unsorted.size(); i++) {
if (unsorted.at(i).x < middleX && unsorted.at(i).y < middleY)sorted[0] = unsorted.at(i);
if (unsorted.at(i).x > middleX && unsorted.at(i).y < middleY)sorted[1] = unsorted.at(i);
if (unsorted.at(i).x < middleX && unsorted.at(i).y > middleY)sorted[2] = unsorted.at(i);
if (unsorted.at(i).x > middleX && unsorted.at(i).y > middleY)sorted[3] = unsorted.at(i);
}
return sorted;
}
+4
source to share