Sohaib
Sohaib

Reputation: 4694

Join close enough contours in 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.

Upvotes: 6

Views: 25417

Answers (2)

Michele mpp Marostica
Michele mpp Marostica

Reputation: 2472

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

wiki link

OpenCV

Upvotes: 5

blacatus
blacatus

Reputation: 330

Hope this link to another similar question works. They solve this problem in a rude way. If it works, go for optimization.

Regarding any libraries with functions that attemp to solve this problem, there are two in openCV (groupRectangles & partition) but they may not solve your problem.

Here is the link: https://dsp.stackexchange.com/questions/2564/opencv-c-connect-nearby-contours-based-on-distance-between-them

Upvotes: 6

Related Questions