# Sorting contours from left to right and top to bottom

I need help to sort contours from left to right and top to bottom. Is there any easy code example?

edit retag close merge delete

Sort by ยป oldest newest most voted

since it's std::vectors, all we need is a fitting 'less' operator, then we can just sort() it.

// mock data for demonstration:
vector<vector<Point>> contours(4);
contours[0].push_back(Point(3,111));
contours[0].push_back(Point(3,121));
contours[1].push_back(Point(81,13));
contours[1].push_back(Point(84,14));
contours[2].push_back(Point(33,55));
contours[2].push_back(Point(36,57));
contours[3].push_back(Point(133,25));
contours[3].push_back(Point(136,27));
for ( int i=0; i<contours.size(); i++ )
cerr << Mat(contours[i]) << endl;

struct contour_sorter // 'less' for contours
{
bool operator ()( const vector<Point>& a, const vector<Point> & b )
{
Rect ra(boundingRect(a));
Rect rb(boundingRect(b));
// scale factor for y should be larger than img.width
return ( (ra.x + 1000*ra.y) < (rb.x + 1000*rb.y) );
}
};

// apply it to the contours:
std::sort(contours.begin(), contours.end(), contour_sorter());

for ( int i=0; i<contours.size(); i++ )
cerr << Mat(contours[i]) << endl;

[3, 111;  3, 121]
[81, 13;  84, 14]
[33, 55;  36, 57]
[133, 25;  136, 27]

[81, 13;  84, 14]
[133, 25;  136, 27]
[33, 55;  36, 57]
[3, 111;  3, 121]

more

Seems good. Many thanks.

( 2014-04-10 05:29:03 -0500 )edit

hello berak,Can you please explain this code in java?

( 2016-06-20 02:22:45 -0500 )edit

^sorry, but i can't (no more java here, atm.)

( 2016-06-20 02:25:18 -0500 )edit

This does not work for me as in single row all my characters do not have same height. :(

( 2018-05-12 06:05:38 -0500 )edit

in python ?

( 2018-10-12 05:15:40 -0500 )edit

@syedd , please do not post answers here, if you hav a question or comment, thank you.

( 2018-10-12 05:18:22 -0500 )edit

Official site

GitHub

Wiki

Documentation