I have a binary image:
In this image I can easily sort the contours that I found from top to bottom and from left to right using the overloaded std::sort
.
I first sort from top to bottom via:
sort(contours.begin(), contours.end(), top_to_bottom_contour_sorter());
Then I sort from left to right by:
for (int i = 0; i < contours.size(); i = i + no_of_contours_horizontally)
{
sort(i, i + no_of_contours_horizontally, left_to_right_contour_sorter);
}
Where top_to_bottom
and left_to_right
are separate functions that I pass to the sort function. And no_of_contours_horizontally
with respect to the first image is three (3).
However this only works if I know the number of contours horizontally. If the image I am using will have varying number of contours horizontally like in this image. contours_sample. The program fails. I could brute force and define for a specific index to change the no of contours found. However, it would limit the program to operate on a specific input instead of being flexible. I am thinking of creating rects or lines that I can overlay on top of the image and with that count the number of contours inside so I can get a value of the number of horizontal contours. If there is a more elegant solution I would appreciate it.
Here are my sorting functions
bool top_to_bottom_contour_sorter(const std::vector<Point> &lhs, const std::vector<Point> &rhs)
{
Rect rectLhs = boundingRect(Mat(lhs));
Rect rectRhs = boundingRect(Mat(rhs));
return rectLhs.y < rectRhs.y;
}
bool left_to_right_contour_sorter(const std::vector<Point> &lhs, const std::vector<Point> &rhs)
{
Rect rectLhs = boundingRect(Mat(lhs));
Rect rectRhs = boundingRect(Mat(rhs));
return rectLhs.x < rectRhs.x;
}
EDIT Here are my current outputs and desired output for each image. Using the first image and my current working code. Current_Output
My desired output for the second image. Desired_Output