I have a 56x1 vector of doubles avg_intensities_double
(range: 0-255) and I want to do k-means clustering to group the values. I use the kmean
function from opencv
. Here is my code:
Mat labels, new_centers;
vector<double> avg_intensities_double(avg_intensities.begin(), avg_intensities.end());
Mat points(avg_intensities_double.size(), 1, CV_32F);
memcpy(points.data, avg_intensities_double.data(), avg_intensities_double.size()*sizeof(uchar));
auto compactness = kmeans(points, 10, labels, TermCriteria(TermCriteria::EPS+TermCriteria::COUNT, 10, 1.0), 10, KMEANS_RANDOM_CENTERS, new_centers);
cout << "labels: " << labels.rows << " x " << labels.cols << '\n' << endl;
for (int i=0; i<labels.rows; i++){
cout << labels.at<int>(i,0) << endl;
}
cout << "new_centers: " << new_centers.rows << " x " << new_centers.cols << '\n' << endl;
for (int i=0; i<new_centers.rows; i++){
cout << new_centers.at<double>(i,0) << endl;
}
I create the input matrix points
and then I copy the values from the vector into the matrix. The result is a 56x1 matrix labels
(with the labels of the cluster that each value belongs to) and a 10x1 matrix new_centers
(with the final center values of the clusters).
When I print the resulted new_centers
matrix I get these values:
new_centers: 10 x 1
7.47421e-238
3.40282e+38
-2.68156e+154
109
103
102
101
5.33389e-315
82.5
1.17119e+166
These are not correct. I expect values in the range 0-255 and not too close to each other, since they are centers of the clusters.
What am I doing wrong here? Is this the right way to do 1-dimensional clustering with k-means? I found one example for points (x,y) clustering but the same approach doesn’t work in my case. Any feedback is appreciated.
I use Ubuntu 18.04 dual boot, c++11, opencv 3.2.0 and my code runs as a ROS melodic node.