In k means clustering, how do I reconstruct just a part of the image?
I performed k means clustering. How do I access the largest cluster?
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include<iostream>
using namespace cv;
int main( int argc, char** argv )
{
Mat newbgr;
Mat src;
Mat image = imread( "/home/manohar/Downloads/images/R-3.PNG", 1 );
imshow( "Original", image );
cvtColor(image, src, CV_BGR2Lab);
Mat samples(src.rows * src.cols, 3, CV_32F);
for( int y = 0; y < src.rows; y++ )
for( int x = 0; x < src.cols; x++ )
for( int z = 0; z < 3; z++)
samples.at<float>(y + x*src.rows, z) = src.at<Vec3b>(y,x)[z];
int clusterCount = 3;
Mat labels;
int attempts = 10;
Mat centers;
kmeans(samples, clusterCount, labels, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 10000, 0.0001), attempts, KMEANS_PP_CENTERS, centers );
Mat new_image( src.size(), src.type() );
for( int y = 0; y < src.rows; y++ )
for( int x = 0; x < src.cols; x++ )
{
int cluster_idx = labels.at<int>(y + x*src.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( "K means", new_image );
waitKey( 0 );
return 0;
}
first problem is, that you won't know, which cluster_idx red is assigned to.
@berak, how do I assign red to the cluster idx and the white to another? Labes? If so please let me know how. I am new to opencv. So in the end, I basically need two images. one with the red circle where the white R occurs black and another with just the white R where everything else occurs black.