简体   繁体   English

使用OpenCV C ++应用K均值后,如何将分割提取为图像?

[英]How to extract segmentation as images after applying K Means using OpenCV C++?

I am new to OpenCV. 我是OpenCV的新手。

My image consists of Red, Green and Blue color pixels spread throughout at random. 我的图像由随机分布的红色,绿色和蓝色像素组成。 I have applied K Means and want to save clustering as different images. 我已应用K均值,并希望将聚类另存为不同的图像。 Suppose if I consider the number of clusters as 3, I want three images saved with the segmentation done by K Means. 假设如果我将聚类的数目视为3,则我希望保存三个图像,并用K Means进行分割。

The language I am using is C++. 我使用的语言是C ++。 And will also be helpful if any suggestions for EMGUCV. 如果对EMGUCV有任何建议,也将有所帮助。

Thankful for responses! 感谢您的答复! Any suggestions are welcome! 欢迎任何建议!

The bestLabels argument to kmeans (you call it 'Labels') lets you specify a cv::Mat where the method will store label indices for all input pixels. kmeansbestLabels参数 (您称之为“标签”)使您可以指定cv :: Mat,该方法将在其中存储所有输入像素的标签索引。 It has the same geometry as the input image. 它具有与输入图像相同的几何形状。

Splitting the output to masks is rather simple. 将输出拆分为掩码非常简单。 The masks can then be saved as files. 然后可以将蒙版另存为文件。 Example code (not tested): 示例代码(未经测试):

for (auto k = 0; k < K; ++k) {
    cv::Mat1b mask = (bestLabels == k);
    cv::imwrite("cluster_" + std::to_string(k) + ".png", mask);
}

Note you probably have to do a bit more for compositing the filename. 请注意,您可能需要做更多的工作来合成文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM