Ask Your Question

Revision history [back]

I use this message from @berak to build this program :

struct Dist {
    bool operator()(const Point& a, const Point &b) {
        return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)) < 15;
    }
};
Mat m=imread("Downloads/kmeans.bmp",CV_LOAD_IMAGE_ANYCOLOR);
vector<Point> data;
for (int i = 0; i<m.rows; i++)
    for (int j = 0;j<m.cols; j++)
        if (m.at<Vec3b>(i,j)!=Vec3b(0,0,0))
            data.push_back(Point(j,i));
vector<int> labels;

partition(data, labels, Dist());
Mat cluster(m.rows,m.cols,CV_8UC1);
for (int i=0;i<data.size();i++)
    cluster.at<uchar>(data[i])=labels[i];
imwrite("label.bmp",cluster);

I must say that with your image it is much more efficiency to use canny or threshold