Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

kmeans clustering convert code to python

I have the following code for k-means clustering , but it is in C++ . I need it in python. I was able to convert just the k-means clustering part into python. Can someone please convert the part where I access the labels and regenerate the image with just the colors into python as soon as possible. Thanks a lot in advance.

#include <opencv2/opencv.hpp> 

using namespace std;
using namespace cv;


void main(void)
{
    Mat img=imread("14780105241945453.png",IMREAD_COLOR);
    cout << "Pixels "<<img.rows*img.cols<<"\n";
    Mat src,srcF;
    cvtColor(img, src, CV_BGR2Lab);
    src.convertTo(srcF, CV_32FC3);
    cout << "Pixels " << srcF.rows*srcF.cols << "\n";
    vector<Vec3f> plan;
    plan.assign((Vec3f*)srcF.datastart, (Vec3f*)srcF.dataend);
    cout << "Pixels " << plan.size() << "\n";
    int clusterCount = 3;
    Mat labels;
    Mat centers;
    kmeans(plan, clusterCount,labels,TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0), 3, KMEANS_PP_CENTERS, centers);
    Mat mask;
    namedWindow("Original", WINDOW_NORMAL);
    imshow("Original", img);
int maxCluster=0,ind=-1;
for (int i = 0; i < clusterCount; i++)
{
    cv::Mat cloud = (labels == i) ;
    namedWindow(format("Cluster %d",i), WINDOW_NORMAL);
    Mat result = Mat::zeros(img.rows, img.cols, CV_8UC3);

    if (cloud.isContinuous())
        mask = cloud.reshape(0, img.rows);
    else
        cout << "error";
    int m=countNonZero(mask);
    if (m > maxCluster)
    {
        maxCluster = m;
        ind=i;
    }
    img.copyTo(result, mask);
    imshow(format("Cluster %d", i), result);
    imwrite(format("Cluster%d.png", i), result);

}
cout<<"Cluster max is "<<ind<<" with "<<maxCluster<<" pixels";
waitKey();
}

Please help me. Thanks a lot in advance and as soon as possible.