【发布时间】:2015-10-05 00:31:58
【问题描述】:
我是opencv的新手,我正在尝试查找并保存kmeaned集群图像的最大集群。我有:
按照 Mercury 和 Bill the Lizard 在以下帖子 (Color classification with k-means in OpenCV) 中提供的方法对图像进行聚类,
通过从 kmeans 输出 (bestLables) 中找到最大的标签计数来确定最大的集群
试图存储构成Point2i数组中最大簇的像素的位置
然而,神秘的是,我发现自己存储的点数明显少于计数 试图找到最大的集群时获得。换句话说: inc
我做错了什么?还是有更好的方法来做我想做的事情?,任何输入将不胜感激。 提前感谢您的宝贵帮助!
#include <iostream>
#include "opencv2/opencv.hpp"
#include<opencv2/highgui/highgui.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat img = imread("pic.jpg", CV_LOAD_IMAGE_COLOR);
if (!img.data)
{
cout << "Could not open or find the image" << std::endl;
return -1;
}
//imshow("img", img);
Mat imlab;
cvtColor(img, imlab, CV_BGR2Lab);
/* Cluster image */
vector<cv::Mat> imgRGB;
int k = 5;
int n = img.rows *img.cols;
Mat img3xN(n, 3, CV_8U);
split(imlab, imgRGB);
for (int i = 0; i != 3; ++i)
imgRGB[i].reshape(1, n).copyTo(img3xN.col(i));
img3xN.convertTo(img3xN, CV_32F);
Mat bestLables;
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);*/
/* Find the largest cluster*/
int max = 0, indx= 0, id = 0;
int clusters[5];
for (int i = 0; i < bestLables.rows; i++)
{
id = bestLables.at<int>(i, 0);
clusters[id]++;
if (clusters[id] > max)
{
max = clusters[id];
indx = id;
}
}
/* save largest cluster */
int cluster = 1, inc = 0;
Point2i shape[2000];
for (int y = 0; y < imlab.rows; y++)
{
for (int x = 0; x < imlab.cols; x++)
{
if (bestLables.data[y + x*imlab.cols] == cluster) shape[inc++] = { y, x };
}
}
waitKey(0);
return 0;
}
【问题讨论】:
-
您是在一张图片上还是在多张图片中进行聚类?您希望两个像素之间的距离影响聚类,还是只影响颜色值?
-
抱歉沉默。是的,我正在对一张图像进行聚类。我不确定距离,但只要它允许我区分集群,即访问我选择的标签的所有像素(例如最大的像素),它对我有用。谢谢!
-
我不知道你是在寻找输入图像中所有相同颜色的像素还是所有相邻的相同颜色的像素(即寻找特定的目的)。如果您想要原始图像中颜色相似且附近的像素,则 k-means 不太可能起作用,因为它不考虑像素位置,只考虑颜色。此外,我要注意的另一件事是每次运行 k-means 时都会出现明显不同的“最大”颜色。如果您遇到这些问题,请告诉我。如果没有,那么看起来 Miki 有你的好去处!
-
也谢谢你!!
标签: c++ algorithm opencv k-means