简体   繁体   中英

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

I am new to 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. Suppose if I consider the number of clusters as 3, I want three images saved with the segmentation done by K Means.

The language I am using is C++. And will also be helpful if any suggestions for 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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