Blob extraction in OpenCV

amr picture amr · Jan 9, 2011 · Viewed 23.7k times · Source

I'm using OpenCV to filter an image for certain colours, so I've got a binary image of the detected regions.

Now I want to erode those areas and then get rid of the smaller ones, and find the x,y coordinates of the largest 'blob'

I was looking for recommendations as to what the best library would be to use? I've seen cvBlob and cvBlobsLib but I'm not too sure how to set them up. Do I want to compile them along with the project or do I want to compile and install them to the system (like I did with OpenCV)?

I'm currently using the Code::Blocks IDE on Ubuntu (although that shouldn't restrict things)

Answer

etarion picture etarion · Jan 9, 2011

You can use findContours to do that, see the opencv manual and a Tutorial to find connected components.


Edit: Code from the tutorial (via Archive.org)

#include <stdio.h>
#include <cv.h>
#include <highgui.h>

int main(int argc, char *argv[])
{
    IplImage *img, *cc_color; /*IplImage is an image in OpenCV*/
    CvMemStorage *mem;
    CvSeq *contours, *ptr;
    img = cvLoadImage(argv[1], 0); /* loads the image from the command line */
    cc_color = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3);

    cvThreshold(img, img, 150, 255, CV_THRESH_BINARY);
    mem = cvCreateMemStorage(0);
    cvFindContours(img, mem, &contours, sizeof(CvContour), CV_RETR_CCOMP,
        CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));


    for (ptr = contours; ptr != NULL; ptr = ptr->h_next) {
        CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 );
        cvDrawContours(cc_color, ptr, color, CV_RGB(0,0,0), -1, CV_FILLED, 8, cvPoint(0,0));
    }

    cvSaveImage("result.png", cc_color);
    cvReleaseImage(&img);
    cvReleaseImage(&cc_color);
    return 0;
}