Ask Your Question
0

Kmeans segmentation

asked 2015-10-29 08:04:25 -0500

thdrksdfthmn gravatar image

I have done a kmeans on an image for segmentation and now I want to restore the colors of the centers in the segmented image (for better visualization):

cv::Mat image = cv::imread(argv[1]);
cv::Mat fImage;
image.convertTo(fImage, CV_32F);
fImage = fImage.reshape(3, image.cols * image.rows);
cv::Mat labels;
cv::Mat centers;
cv::kmeans(fImage, 10, labels, cv::TermCriteria(), 3, cv::KMEANS_RANDOM_CENTERS, centers);
cv::Mat segmented = labels.reshape(1, image.rows);
segmented.convertTo(segmented, CV_8UC3);

but segmented contains just the indexes in the centers. Is there a fast way to replace the values of segmented by the values of centers?

I know I can do the for loop in for loop to replace the values, but I thought of something like LUT; unfortunately, this runs only on 256 lut Mat, but centers is not a 256 one channel Mat. Is there another way to do it?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2015-10-29 10:00:03 -0500

LBerger gravatar image

updated 2015-10-29 10:56:01 -0500

I haven't check channels but it seems working for lena

cv::Mat image = cv::imread("f:/lib/opencv/samples/data/lena.jpg");
cv::Mat fImage;
image.convertTo(fImage, CV_32F);
fImage = fImage.reshape(3, image.cols * image.rows);
cv::Mat labels;
cv::Mat centers;
cv::kmeans(fImage, 10, labels, cv::TermCriteria(), 3, cv::KMEANS_RANDOM_CENTERS, centers);
cout<<centers<<endl;
cv::Mat segmented = labels.reshape(1, image.rows);
cv::Mat im = cv::Mat::zeros(image.size(), CV_8UC3);

for (int i = 0; i < centers.rows; i++)
{
    cv::Mat mask = (segmented == i);
    cv::Vec3b v(centers.at< float >(i, 0), centers.at< float >(i, 1), centers.at< float >(i, 2));
    im.setTo(v,mask);    
}
segmented.convertTo(segmented, CV_8UC3);
cv::imshow("Segmented color", im);
cv::imshow("Segmented", segmented);
cv::imwrite("segemented.png", segmented);
cv::waitKey();
edit flag offensive delete link more

Comments

It is not really what I searched for, but it works... I like the masks part, I think it is useful. Thanks.

thdrksdfthmn gravatar imagethdrksdfthmn ( 2015-10-29 10:20:59 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2015-10-29 08:04:25 -0500

Seen: 365 times

Last updated: Oct 29 '15