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

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)

Thanks in advance.


2 Answers 2


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.

  • $\begingroup$ Bill Xia and nivag thanks to you both. I combined your suggestnions how to solve it and it works. $\endgroup$
    – Maerorek
    May 13, 2014 at 13:58

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

black-wihte image

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;
    IplImage *im = cvLoadImage("2Dpg6.jpg");

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

    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
        rec = cvBoundingRect(contours,1);

    return 0;
  • $\begingroup$ Bill Xia and nivag thanks to you both. I combined your suggestnions how to solve it and it works. $\endgroup$
    – Maerorek
    May 13, 2014 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.