C++ OpenCV kmeans聚类
时间: 2023-08-13 16:04:12 浏览: 162
C++中使用OpenCV进行kmeans聚类的代码示例如下:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
Mat img = imread("image.jpg");
Mat samples(img.rows * img.cols, 3, CV_32F);
for (int y = 0; y < img.rows; y++) {
for (int x = 0; x < img.cols; x++) {
for (int z = 0; z < 3; z++) {
samples.at<float>(y + x * img.rows, z) = img.at<Vec3b>(y, x)\[z\];
}
}
}
int clusterCount = 8;
Mat labels;
int attempts = 5;
Mat centers;
kmeans(samples, clusterCount, labels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0), attempts, KMEANS_RANDOM_CENTERS, centers);
Mat new_image(img.size(), img.type());
for (int y = 0; y < img.rows; y++) {
for (int x = 0; x < img.cols; x++) {
int cluster_idx = labels.at<int>(y + x * img.rows, 0);
new_image.at<Vec3b>(y, x)\[0\] = centers.at<float>(cluster_idx, 0);
new_image.at<Vec3b>(y, x)\[1\] = centers.at<float>(cluster_idx, 1);
new_image.at<Vec3b>(y, x)\[2\] = centers.at<float>(cluster_idx, 2);
}
}
imshow("Original Image", img);
imshow("Clustered Image", new_image);
waitKey(0);
return 0;
}
```
这段代码首先读取一张图像,然后将图像的像素值重塑为一个Mx3大小的数组,其中M是图像中的像素数。接下来,使用kmeans函数对像素值进行聚类,指定聚类的数量为8。最后,根据聚类结果将像素值替换为对应的聚类中心值,生成聚类后的图像。
#### 引用[.reference_title]
- *1* *2* [[C++] Kmeans算法实现](https://blog.csdn.net/weixin_44179561/article/details/126208335)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [OpenCV52:OpenCV中的Kmeans聚类](https://blog.csdn.net/uncle_ll/article/details/122608227)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文