Contours sorting. Are contours returned by findContours() sorted somehow? It seems that they aren't.

In fact, I've got 1D std::vector of centroids of contours. (Got with the help of moments())

I need to sort these centroids and "reduce" this 1D vector into 2D vector (vector of vectors) so that I could easily navigate among these centroids in two dimensional domain by i and j indexes.

I should also insert so called "missed" centroids (e.g. as negative ones) to make 2D array square or rectangular (alignment). Centroids form fine grid so I can measure distances between them on x and y coordinates to find out is there a "missed" centroid or two or several ones between two existing ones.

Couldn't you suggest an easy simple way to perform this?

edit retag close merge delete

Sort by » oldest newest most voted  Hi @konstunn!

Contours are aligned in opencv as a hierarchy of parent & child contours based on the type of Contour approximation method you choose. For detailed explanation refer this wiki.

If you are having a Vector of Points & you want to sort these points you can refer this code:

bool SortbyXaxis(const Point & a, const Point &b)
{
return a.x < b.x;
}
bool SortbyYaxis(const Point & a, const Point &b)
{
return a.Y < b.Y;
}

vector<Point> Points;
sort( Points.begin(), Points.end(), SortbyYaxis );
sort( Points.begin(), Points.end(), SortbyXaxis );

more

I've got vector<Point2f> instead of vector<Point>. Does it really matter...? And this kind of code doesn't work on MinGW for me. :( It causes segmentation fault.

Sorry, but this is not my case, not my problem. My problem is segmentation fault while step through compare function.

But std::stable_sort() instead of std::sort() works fine!