# Color and circle detection in image

I try to detect and count circles in image (for example smarties)

I use HSL color space. But I am not able to distiguish colors od the same color if they are in touch. I try to erode and dilate picture. But result is the same, I have only some blobs(connected components) od the same color. Do you have some general algorithm for this problem?

(I try to do that with EMGUCV library)

If I understand you correctly, you erode, then dilate then look for the colour of your blobs. Erosion then dilation is an opening operator. As you can hopefully see that's not going to do too much to seperate the blobs.

I would suggest that you do not really need to dilate. If you just erode enough so that the blobs seperate. You can then mark a pixel in each blob (centre is probably a good bet), which should now be seperated, and find the colour of that pixel in the original image.

• Bill Xia and nivag thanks to you both. I combined your suggestnions how to solve it and it works. – Maerorek May 13 '14 at 13:58

There is no need to Dilate. Here is my segmentation results:

And here is my code using OpenCV:

#include <iostream>
using namespace std;
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
using namespace cv;

int main()
{
int ht,wt;
ht=im->height,wt=im->width;
cvShowImage("RGB",im);

IplImage *img = cvCreateImage(cvGetSize(im),8,1);
cvCvtColor(im,img,CV_RGB2GRAY);

CvRect rec;
CvSeq *contours;
CvMemStorage *storage=cvCreateMemStorage(0);
IplImage *img2 = cvCreateImage(cvGetSize(im),8,1);

cvThreshold(img,img2,30,255,CV_THRESH_BINARY);  // image segmentation
cvErode(img2,img2,NULL,7);  // erode
cvShowImage("BW",img2);  // show black-wihte image
cvFindContours(img2,storage,&contours,sizeof(CvContour),CV_RETR_CCOMP);  // find contours
while(contours){
rec = cvBoundingRect(contours,1);
cvRectangleR(img,rec,cvScalar(255));
contours=contours->h_next;
}
cvShowImage("Gray",img);

cvWaitKey(0);
return 0;
}

• Bill Xia and nivag thanks to you both. I combined your suggestnions how to solve it and it works. – Maerorek May 13 '14 at 13:59