Table of Contents

Method Kmeans

Namespace
OpenCvSharp
Assembly
OpenCvSharp.dll

Kmeans(InputArray, int, InputOutputArray, TermCriteria, int, KMeansFlags, OutputArray)

Finds centers of clusters and groups input samples around the clusters.

public static double Kmeans(InputArray data, int k, InputOutputArray bestLabels, TermCriteria criteria, int attempts, KMeansFlags flags, OutputArray centers = default)

Parameters

data InputArray

Data for clustering. An array of N-Dimensional points with float coordinates is needed.

k int

Number of clusters to split the set by.

bestLabels InputOutputArray

Input/output integer array that stores the cluster indices for every sample.

criteria TermCriteria

The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops.

attempts int

Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness (see the last function parameter).

flags KMeansFlags

Flag that can take values of cv::KmeansFlags

centers OutputArray

Output matrix of the cluster centers, one row per each cluster center.

Returns

double

The function returns the compactness measure that is computed as \f[\sum _i | \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} | ^2\f] after every attempt. The best (minimum) value is chosen and the corresponding labels and the compactness value are returned by the function. Basically, you can use only the core of the function, set the number of attempts to 1, initialize labels each time using a custom algorithm, pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering.