作为替代手动重塑输入矩阵,可以使用的OpenCV reshape函数来实现类似的结果用更少的代码。下面是降低颜色与K-means法(在Java中)计数的我的工作实现:
private final static int MAX_ITER = 10;
private final static int CLUSTERS = 16;
public static Mat colorMapKMeans(Mat img, int K, int maxIterations) {
Mat m = img.reshape(1, img.rows() * img.cols());
m.convertTo(m, CvType.CV_32F);
Mat bestLabels = new Mat(m.rows(), 1, CvType.CV_8U);
Mat centroids = new Mat(K, 1, CvType.CV_32F);
Core.kmeans(m, K, bestLabels,
new TermCriteria(TermCriteria.COUNT | TermCriteria.EPS, maxIterations, 1E-5),
1, Core.KMEANS_RANDOM_CENTERS, centroids);
List<Integer> idx = new ArrayList<>(m.rows());
Converters.Mat_to_vector_int(bestLabels, idx);
Mat imgMapped = new Mat(m.size(), m.type());
for(int i = 0; i < idx.size(); i++) {
Mat row = imgMapped.row(i);
centroids.row(idx.get(i)).copyTo(row);
}
return imgMapped.reshape(3, img.rows());
}
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Highgui.imwrite("result.png",
colorMapKMeans(Highgui.imread(args[0], Highgui.CV_LOAD_IMAGE_COLOR),
CLUSTERS, MAX_ITER));
}
OpenCV的读取图像到二维,3信道矩阵。首先拨打reshape
- img.reshape(1, img.rows() * img.cols());
- 实质上将3个通道展开为列。在结果矩阵中,一行对应于输入图像的一个像素,而3列对应于RGB分量。
后K-means算法完成其工作,并且颜色映射得到了应用,我们再次呼吁reshape
- imgMapped.reshape(3, img.rows())
,但现在滚动体列回通道,减少行数为原始图像的行数,从而找回了原始矩阵格式,但只有减少的颜色。
我想知道你在循环之前在clusterCount变量声明中所做的事情,以及你在kmeans之后的for循环结尾所做的事情。你认为用这些信息更新答案是可能的吗?谢谢! – 2013-02-11 19:17:27
第一个循环将来自图像的数据从(行,列,3)矩阵重新排列到(rows * cols,3)矩阵(每个像素一行)。最后的循环将图像中的每个像素替换为相应的聚类中心以进行可视化。 – sietschie 2013-02-12 09:25:07
是否可以使用'Mat :: reshape()'而不是嵌套for循环? – Jayesh 2016-10-26 13:41:16