Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join close enough contours in openCV

Tags:

c++

opencv

I have a set of detected contours/blobs from an image. The problem is that some of the blobs are a split during blob detection and smoothing. I have tried to use the following code.

Mat outlines=Mat::zeros(m3.size(),CV_8UC3);
findContours(m3,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE,Point(0,0));
//Approximate Contours
std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
for( int i = 0; i < contours.size(); i++ ) {
    approxPolyDP(cv::Mat(contours[i]), contours_poly[i], 5, true );
    std::vector<cv::Point> hull;
    cv::convexHull(cv::Mat(contours_poly[i]),hull);
    cv::Mat hull_points(hull);
    cv::RotatedRect rotated_bounding_rect = minAreaRect(hull_points);
    Point2f vertices[4];
    if(rotated_bounding_rect.size.area()==0){
        continue;
    }
    rotated_bounding_rect.points(vertices);
    for (int i = 0; i < 4; ++i)
    {
        cv::line(outlines, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 1, CV_AA);
    }
}

The problem is that even though these contours are detected and joined using the approxPolyDP method it leads to the disappearance of some small blobs even when they are alone and do not have any other blobs in the vicinity.

What I want is for those blobs who are very near to be joined or at least one of them should be deleted from my list of contours and all the rest should be preserved.

Below are the initial and final images which would make my question more clear. Initial Image:
http://sdrv.ms/1bp8x89
Final Image:
http://sdrv.ms/1bp8tp5

As we can see in the final image the small blob on the right side of the image goes missing even when some of the blobs have not been joined properly.

Also this technique is taking a few seconds for a single frame. Given a video this technique becomes very inefficient.

Please suggest some remedies.

like image 480
Sohaib Avatar asked Oct 01 '13 18:10

Sohaib


1 Answers

I can suggest you a morphological transformation of your image called dilation

wiki link

OpenCV

like image 160
Michele mpp Marostica Avatar answered Oct 09 '22 07:10

Michele mpp Marostica