Kmeans algorithm is mainly used to realize automatic clustering, and is an unsupervised machine learning algorithm, which is widely used. Such a function is provided in opencv3.0, and it is very convenient for the automatic clustering to be realized by direct invocation.
Function Prototypes:
Double int int int flags, Outputarray Centers=noarray ())
There are 7 parameters, each of which indicates:
Data: Automatic clustering is required, typically a mat. A floating-point matrix, one sample per behavior.
K: Take a few classes and compare the key parameters.
Bestlabels: Returns the category tag, integer number.
Criteria: The criterion for the end of the algorithm, the maximum number of iterations to get the desired precision
Attempts: Determine the minimum number of clusters of a sample for a class, such as a value of 3 o'clock, when a sample cluster is 3 times the same class.
Flags: Determines how the cluster heart is calculated. There are three values to choose from:kmeans_random_centers indicates random initialization of the cluster heart. kmeans_pp_centers indicates that the cluster heart is initialized with the kmeans++ algorithm (not used),kmeans_use_initial_labels indicates that the cluster is initialized with the value given by the user for the first cluster, Cluster hearts are automatically determined after several clusters.
Centers: Used to initialize the cluster heart. is related to the selection of the previous flags parameter. This parameter can be omitted if the kmeans_random_centers is chosen randomly to initialize the cluster heart.
Example Picture:
Learn PS tracing know, hair silk in the drawing, is very difficult. Here we use Kmeans automatic clustering for automatic keying.
The idea is to take the three-channel value of each pixel of the picture as a feature, so we get a feature matrix data of 3 columns of n rows, and then use this feature matrix for Kmeans.
Code:
#include"stdafx.h"#include"opencv2\opencv.hpp"#include<iostream>using namespacestd;using namespaceCV;intMain () {Const intMax_clusters =5; VEC3B colortab[]={vec3b (0,0,255), vec3b (0,255,0), vec3b (255, -, -), vec3b (255,0,255), vec3b (0,255,255) }; Mat Data,labels; Mat pic= Imread ("D:/woman.png"); for(inti =0; I < pic.rows;i++) for(intj =0; J < Pic.cols; J + +) {vec3b point= pic.at<vec3b>(i, j); Mat tmp= (mat_<float> (1,3) << point[0], point[1], point[2]); Data.push_back (TMP); } //based on the browse image, determine k=3Kmeans (data,3, labels, termcriteria (termcriteria::eps + Termcriteria::count,Ten,1.0), 3, kmeans_random_centers); intn =0; //Show clustering results, different categories are displayed in different colors for(inti =0; i < pic.rows; i++) for(intj =0; J < Pic.cols; J + +) { intClusteridx = labels.at<int>(n); pic.at<Vec3b> (i, j) =Colortab[clusteridx]; N++; } imshow ("pic", pic); Waitkey (0); return 0;}
Results:
The effect is not very ideal, after all, is fully automatic.
Using Kmeans in Opencv3 to realize cutout function