1

我想使用我在 DLIB 库中找到的 k 均值聚类算法和后来的光谱聚类算法对 BW 图像进行聚类。我目前的结果非常奇怪(至少对我而言),我将不胜感激。

原图:

图像到集群

目前的结果是:

结果 1

结果 2

结果 3

cv::Mat inputImage = cv::imread("lixo.png");
cv::cvtColor(inputImage, inputImage, CV_RGB2GRAY);
cv::imshow("Display Image", inputImage);
cv::waitKey(0);    
// from cv::mat to dlib vector of points
dlib::matrix<double,2,1> sample_point;
std::vector<dlib::matrix<double,2,1>> samples;
for( long i = 0; i < inputImage.rows; ++i) {
    for( long j = 0; j < inputImage.cols; ++j ) {
        if (inputImage.at<uchar>(i,j) == (uchar)255) {
            sample_point(0) = i;
            sample_point(1) = j;
            samples.push_back(sample_point);
        }
    }
}


// typedef for the kind of kernel we want to use
typedef dlib::radial_basis_kernel<dlib::matrix<double,2,1>> kernel_type;
// the kcentroid object
dlib::kcentroid<kernel_type> kc(kernel_type(0.1),0.01, 8);
// kkmeans object and tell it to use kcentroid objects
dlib::kkmeans<kernel_type> test(kc);
// tell the kkmeans we want 3 clusters
int nclus = 3;
test.set_number_of_centers(nclus);
// pick some initial centers for the k-means algorithm
std::vector<dlib::matrix<double,2,1>> initial_centers;
pick_initial_centers(nclus,initial_centers, samples,test.get_kernel());
// now run the k-means algorithm on our set of samples
test.train(samples, initial_centers);     
// show result
int r = inputImage.rows;
int c = inputImage.cols;
cv::Mat result1 = cv::Mat::zeros(r, c, CV_8UC1);
cv::Mat result2 = cv::Mat::zeros(r, c, CV_8UC1);
cv::Mat result3 = cv::Mat::zeros(r, c, CV_8UC1);     
int n1 = 0;
int n2 = 0;
int n3 = 0;
std::cout <<  " Result" << std::endl;
for (long i = 0; i < samples.size(); ++i) {
    sample_point = samples[i];
    int result = test(sample_point);
    if(result == 0) {
        n1++;
        result1.at<uchar>(sample_point(0), sample_point(1)) = (uchar)255;
    } else if(result == 1) {
        n2++;
        result2.at<uchar>(sample_point(0), sample_point(1)) = (uchar)255;
    } else if(result == 2) {
        n3++;
        result3.at<uchar>(sample_point(0), sample_point(1)) = (uchar)255;
    }
}     
cv::imshow("result1", result1);
cv::imshow("result2", result2);
cv::imshow("result3", result3);
cv::waitKey(0);
4

0 回答 0