在 OpenCV 中使用 k-means 进行颜色分类 [英] Color classification with k-means in OpenCV
问题描述
我想用 K-Means
算法对大量图像进行聚类.我想设置集群,以便每个集群代表图像的主色或色调.我在论文 使用 K-Means 的彩色图像聚类 中读到了一些相关内容
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 image. I've read something about this in the paper Colour Image Clustering using K-Means
有人有想法在 OpenCV 中执行此操作吗?
Does someone have an idea to do this in OpenCV?
也许我可以比较每张图片的直方图.但是如果我有很多照片,那需要很长时间
Maybe I can compare the histograms of each image. But if I have a lot of pictures it takes a very long time
推荐答案
您可以对图像进行矢量化,使每一行都是一组 RGB,然后使用 cv::kmeans
进行聚类,例如:
You can vectorize your image so each row is a set of RGB, and than use cv::kmeans
to cluster, something like:
std::vector<cv::Mat> 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();
这篇关于在 OpenCV 中使用 k-means 进行颜色分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!