c++ - OpenCV - 如何在灰度图像上应用 Kmeans?
问题描述
我正在尝试使用 Kmeans 对灰度图像进行聚类。
首先,我有一个问题:
Kmeans 是聚类 Mat 的最佳方法还是有更新更有效的方法?
其次,当我尝试这个时:
Mat degrees = imread("an image" , IMREAD_GRAYSCALE);
const unsigned int singleLineSize = degrees.rows * degrees.cols;
Mat data = degrees.reshape(1, singleLineSize);
data.convertTo(data, CV_32F);
std::vector<int> labels;
cv::Mat1f colors;
cv::kmeans(data, 3, labels, cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 10, 1.), 2, cv::KMEANS_PP_CENTERS, colors);
for (unsigned int i = 0; i < singleLineSize; i++) {
data.at<float>(i) = colors(labels[i]);
}
Mat outputImage = data.reshape(1, degrees.rows);
outputImage.convertTo(outputImage, CV_8U);
imshow("outputImage", outputImage);
结果 ( outputImage
) 为空。
当我尝试colors
在 for 循环中相乘时,出现data.at<float>(i) = 255 * colors(labels[i]);
此错误:
未处理的异常:整数除以零。
如何正确聚类灰度图像?
解决方案
在我看来,您错误地将标签和颜色信息解析为输出矩阵。
K-means 返回此信息:
标签- 这是一个包含所有集群标签的 int 矩阵。它是一个大小为 TotalImagePixels x 1 的“列”矩阵。
中心- 这就是您所说的“颜色”。这是一个包含聚类中心的浮点矩阵。该矩阵的大小为 NumberOfClusters x featureMean。
在这种情况下,当您使用BGR 像素作为“特征”时,请考虑 Centers 有 3 列:B 通道的一个平均值,G 通道的一个平均值,最后一个 R 通道的平均值。
所以,基本上你遍历(普通)标签矩阵,检索标签,使用这个值作为中心矩阵中的索引来检索 3 种颜色。
一种方法如下,使用自动数据说明符并循环输入图像(这样我们可以更容易地索引每个输入标签):
//prepare an empty output matrix
cv::Mat outputImage( inputImage.size(), inputImage.type() );
//loop thru the input image rows...
for( int row = 0; row != inputImage.rows; ++row ){
//obtain a pointer to the beginning of the row
//alt: uchar* outputImageBegin = outputImage.ptr<uchar>(row);
auto outputImageBegin = outputImage.ptr<uchar>(row);
//obtain a pointer to the end of the row
auto outputImageEnd = outputImageBegin + outputImage.cols * 3;
//obtain a pointer to the label:
auto labels_ptr = labels.ptr<int>(row * inputImage.cols);
//while the end of the image hasn't been reached...
while( outputImageBegin != outputImageEnd ){
//current label index:
int const cluster_idx = *labels_ptr;
//get the center of that index:
auto centers_ptr = centers.ptr<float>(cluster_idx);
//we got an implicit VEC3B vector, we must map the BGR items to the
//output mat:
clusteredImageBegin[0] = centers_ptr[0];
clusteredImageBegin[1] = centers_ptr[1];
clusteredImageBegin[2] = centers_ptr[2];
//increase the row "iterator" of our matrices:
clusteredImageBegin += 3; ++labels_ptr;
}
}
推荐阅读
- android - 动态包含 dagger2 模块
- flutter - 等待调试连接时出错:Bad state: No element Flutter VS Code
- python - Python lint 规则避免没有尾随逗号的单值括号
- reactjs - 键入'{ src:字符串;}' 不可分配给类型 'SVGProps
- c++ - CIP 协议:cip 协议中数据的结构和值
- unit-testing - 在 golang 中模拟依赖项是否需要 DI(依赖项注入)?
- git - 为什么按名称删除远程分支会产生错误,而按引用删除则不会?
- flutter - 在开始 Flutter 之前我需要了解 Dart
- powerbi - PowerBI-JavaScript API 中 RDL(分页)报表的过滤器(参数)
- python - Flask:确定请求发往哪个 IP 地址