AruniRC
AruniRC

Reputation: 5148

cvFindContours() not detecting separate components

I'm trying to find connected components present (if any) within a small region of an image. However the cvFindContours() function is grouping visibly separate components into one single component making further calculations incorrect.

How do I get the separate components within the region? (Colored different components as detected by the function).

The code is as follows:

    IplImage* cc_img = cvCreateImage( cvGetSize(src), src->depth, 3 );
cvSetZero(cc_img);
CvScalar(ext_color);

CvMemStorage *mem;
mem = cvCreateMemStorage(0);
CvSeq *contours = 0;
CvSeq *ptr;
int n_cont = 0;
int n = cvFindContours( src, mem, &contours, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

for (ptr = contours; ptr != NULL; ptr = ptr->h_next) 
{
    n_cont++;

    ext_color = CV_RGB( rand()&255, rand()&255, rand()&255 ); //randomly coloring different contours
    cvDrawContours(cc_img, ptr, ext_color, CV_RGB(0,0,0), -1, CV_FILLED, 8, cvPoint(0,0));        
}

enter image description here

"CEL" is considered to be a single component!

Upvotes: 3

Views: 1466

Answers (2)

Matthias Odisio
Matthias Odisio

Reputation: 2038

I don't use OpenCV, but I verified with Mathematica that you probably want to specify that two components should be connected only through their top, bottom, left, and right neighbors. If you consider the full 8 neighbors, then all the three letters are connected, as you showed:

comp = MorphologicalComponents[img, CornerNeighbors -> False];
Colorize[comp]

enter image description here

Upvotes: 3

jeff7
jeff7

Reputation: 2182

Try applying some morphological filtering such as cvErode or cvMorphologyEx(..., CV_MOP_OPEN) to expand the distance between the letters before running cvFindContours.

Upvotes: 1

Related Questions