Color classification with k-means in OpenCV

前端 未结 1 1349
执念已碎
执念已碎 2020-12-30 16:43

I want to cluster a lot of images with the K-Means Algorithm. I want to set up the clusters, so that each cluster represent the dominant color or the hue of the

1条回答
  •  Happy的楠姐
    2020-12-30 17:41

    You can vectorize your image so each row is a set of RGB, and than use cv::kmeans to cluster, something like:

        std::vector imgRGB;
        cv::split(img,imgRGB);
        int k=5;
        int n = img.rows *img.cols;
        cv::Mat img3xN(n,3,CV_8U);
        for(int i=0;i!=3;++i)  
          imgRGB[i].reshape(1,n).copyTo(img3xN.col(i));
        img3xN.convertTo(img3xN,CV_32F);
        cv::Mat bestLables;
        cv::kmeans(img3xN,k,bestLables,cv::TermCriteria(),10,cv::KMEANS_RANDOM_CENTERS );
        bestLables= bestLables.reshape(0,img.rows);
        cv::convertScaleAbs(bestLables,bestLables,int(255/k));
        cv::imshow("result",bestLables);
        cv::waitKey();
    

    0 讨论(0)
提交回复
热议问题