Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I would suggest morphological operator to close the gap before to find contour.

In this case you can use MORPH_CLOSE with a vertical kernel where height >= as distance you want to connect.For example the code below produces this result

Morph Close image description than contour image description

Mat src,dst,bw,connected;
src= imread("../img/numbers.png");
inRange(src, Scalar(200,200,200), Scalar(255,255,255), bw);
// define your kernel as vertical line
int maxDistance = 4; //as distance you want to connect
Mat kernel = Mat(Size(3, maxDistance), CV_8UC1, Scalar(0));
//vert line in the middle
line(kernel, Point(kernel.cols/ 2, 0), Point(kernel.cols / 2, kernel.rows), CL_WHITE, 1);
cv::morphologyEx(bw, connected, MORPH_CLOSE, kernel);
imshow("Connected Numbers", connected);
vector<vector<Point>> contours;
findContours(connected, contours, RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
for (size_t i = 0; i < contours.size(); i++)
{
    Rect rr = boundingRect(contours[i]);
    rectangle(src, rr, CL_GREEN, 1);
}
imshow("Connected Rects", src);
waitKey(0);

do not use too much height because you will close "5" too