如何设置K-means的初始中心

how to set initial centers of K-means openCV c++

本文关键字:K-means 何设置 设置      更新时间:2023-10-16

我正在尝试使用OpenCv和Kmeans对图像进行分割,我刚刚实现的代码如下:

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
int main(int, char** argv)
{
    Mat src, Imagen2, Imagris, labels, centers,imgfondo;
    src = imread("C:/Users/Sebastian/Documents/Visual Studio 2015/Projects/ClusteringImage/data/leon.jpg");
    imgfondo = imread("C:/Users/Sebastian/Documents/Visual Studio 2015/Projects/ClusteringImage/data/goku640.jpg");
    if (src.empty()|| imgfondo.empty())
    {
        printf("Error al cargar imagenes");
        waitKey();
        return -1;
    }
    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];
    //KMEANS_USE_INITIAL_LABELS
    kmeans(samples, 2, labels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0), 3, KMEANS_USE_INITIAL_LABELS, centers);
    Mat new_image(src.size(), src.type());
    int cluster;
    if (centers.at<float>(0, 1) > centers.at<float>(1, 1))  cluster = 0;
    else        cluster = 1;
    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);
            if (cluster_idx == cluster)
            {
                new_image.at<Vec3b>(y, x)[0] = imgfondo.at<Vec3b>(y, x)[0];
                new_image.at<Vec3b>(y, x)[1] = imgfondo.at<Vec3b>(y, x)[1];
                new_image.at<Vec3b>(y, x)[2] = imgfondo.at<Vec3b>(y, x)[2];
            }
            else
            {
                new_image.at<Vec3b>(y, x)[0] = src.at<Vec3b>(y, x)[0];
                new_image.at<Vec3b>(y, x)[1] = src.at<Vec3b>(y, x)[1];
                new_image.at<Vec3b>(y, x)[2] = src.at<Vec3b>(y, x)[2];
            }
        }
    imshow("Original image", src);
    imshow("clustered image", new_image);
    waitKey();
}

它工作得很好,它做我想要的,但我想设置我自己的初始中心值。我已经读到,它可以使用标志"KMEANS_USE_INITIAL_LABELS"来完成,但我不太确定如何使用它,以及如何以及在哪里设置初始值。谢谢。

该功能允许您直接设置初始标签,而不是中心。幸运的是,由于k-means在赋值和更新步骤之间交替,您可以间接地获得想要的效果。


From the docs:

labels -输入/输出整数数组,存储每个样本的簇索引。

KMEANS_USE_INITIAL_LABELS在第一次(也可能是唯一一次)尝试期间,使用用户提供的标签,而不是从初始中心计算它们。对于第二次和进一步的尝试,使用随机或半随机中心。使用KMEANS_*_CENTERS标志之一来指定确切的方法。

所以,文档说的是你可以设置初始的标签。如果你想这样做,在你的代码
kmeans(samples, 2, labels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0), 3, KMEANS_USE_INITIAL_LABELS, centers);

初始化第三个参数为输入标签(用于第一次迭代)。


如果您想获得设置初始中心的效果,您可以这样做:

  1. 决定什么是中心

  2. 计算标签,就像算法在分配步骤中做的那样。

  3. 将结果标签传递给函数。