Ask Your Question
5

Sorting contours from left to right and top to bottom

asked 2014-04-10 04:11:14 -0600

Solution Developer gravatar image

updated 2020-11-30 03:25:42 -0600

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

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
9

answered 2014-04-10 04:44:11 -0600

berak gravatar image

updated 2014-04-10 04:46:57 -0600

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]
edit flag offensive delete link more

Comments

Seems good. Many thanks.

Solution Developer gravatar imageSolution Developer ( 2014-04-10 05:29:03 -0600 )edit

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

Hardik Patel gravatar imageHardik Patel ( 2016-06-20 02:22:45 -0600 )edit

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

berak gravatar imageberak ( 2016-06-20 02:25:18 -0600 )edit

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

prashant gravatar imageprashant ( 2018-05-12 06:05:38 -0600 )edit

in python ?

syedd gravatar imagesyedd ( 2018-10-12 05:15:40 -0600 )edit

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

berak gravatar imageberak ( 2018-10-12 05:18:22 -0600 )edit

Question Tools

3 followers

Stats

Asked: 2014-04-10 04:11:14 -0600

Seen: 14,758 times

Last updated: Apr 10 '14