Previous blog wrote K-means clustering algorithm and improved K-means algorithm, this blog post on the corresponding MATLAB and C + + code.
The following is the MATLAB code, the realization uses the K-means to divide:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Function: Realize how to use Kmeans clustering to realize the segmentation of image; Time: -- - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function kmeans_segmentation() Clear;close ALL;CLC;Percent Read Test imageim = Imread (' city.jpg '); Imshow (IM), title (' imput image ');Percent conversion Image color space to get samplesCform = Makecform (' Srgb2lab '); Lab = Applycform (Im,cform); AB = Double (Lab (:,:,2:3)); nrows =size(Lab,1); Ncols =size(Lab,2); X =Reshape(Ab,nrows*ncols,2)'; Figure, Scatter (X (1,:) ' )X2,:)', 3, 'filled '), title (' Image 2 '); box on;% display spatial distribution of two-dimensional sample after color space conversion Kmeans Clustering of sample space by percentK =5;% number of clustersMax_iter = -;% maximum number of iterations [Centroids, labels]= Run_kmeans (X, K, max_iter);Percent display cluster segmentation resultsFigure, Scatter (X (1,:)', X (2,:) '3, labels,' filled '), title (' Image 3 ');% show two-dimensional sample space clustering effectHold on; Scatter (Centroids (1,:), Centroids (2,:), -,' R ',' filled ') Hold on; Scatter (Centroids (1,:), Centroids (2,:), -,' G ',' filled ') box on; Hold off;%print-dpdf 2d2.pdfPixel_labels =Reshape(Labels,nrows,ncols); Rgb_labels = Label2rgb (pixel_labels); Figure, Imshow (Rgb_labels), title (' segmented Image ');%print-dpdf seg.pdf End function [centroids, labels] = Run_kmeans(X, K, max_iter) % This function implements Kmeans clustering % input Parameters: % x is the input sample set, DxN % k is the number of cluster centers % Max_iter is the maximum number of iterations for the Kemans cluster % output Parameters: % centroids is a cluster center dxk % labels is the category tag for the sample Percent percent using k-means++ algorithm to initialize cluster centerCentroids = X (:,1+round(Rand*(sizeX2)-1))); Labels =ones(1,sizeX2)); for I=2: K D = X-centroids (:, labels); D = Cumsum (sqrt(Dot(D,d,1)));ifDEnd) ==0, Centroids (:,I: k) = X (:,ones(1. KoI+1));return;EndCentroids (:,I) = X (:,Find(Rand< D/D (End),1));[~,labels]= Max (Bsxfun(@minus,2*Real(centroids '*X),Dot(Centroids,centroids,1).')); End-percent-percent standard Kmeans algorithm for iter = 1:max_iter for i = 1:k, L = labels==i; Centroids (:, i) = SUM (X (:, L), 2)/sum (l); End [~,labels] = max (Bsxfun (@minus, 2*real (centroids '*X),Dot(Centroids,centroids,1).'), [],1]; End End
The implementation results are as follows:
Figure one is a picture of a handsome Coliu De Hua jpg; figure two is to convert the image of the RGB space into a distribution map of the lab space; Figure three is the image of the lab space clustering, a total of three categories, figure four is the clustering of the lab diagram converted to the original RGB map.
The following are the VS+OPENCV implementations:
#include "opencv2/highgui/highgui.hpp"#include "opencv2/core/core.hpp"#include <iostream>using namespaceCvusing namespace STD;intMainint /*argc*/,Char**/*argv*/){Const intMax_clusters =5; Scalar colortab[] = {scalar (0,0,255), Scalar (0,255,0), Scalar (255, -, -), Scalar (255,0,255), Scalar (0,255,255) }; Mat img ( -, -, CV_8UC3); RNG RNG (12345); for(;;) {intK, Clustercount = Rng.uniform (2, max_clusters+1);intI, Samplecount = Rng.uniform (1,1001); Mat points (Samplecount,2, cv_32f), labels; Clustercount = MIN (Clustercount, Samplecount); Mat centers;/ * Generate random sample from Multigaussian distribution * / for(k =0; K < Clustercount; k++) {Point Center; Center.x = Rng.uniform (0, Img.cols); Center.y = Rng.uniform (0, img.rows); Mat pointchunk = Points.rowrange (k*samplecount/clustercount, k = = Clustercount-1? Samplecount:(K +1) *samplecount/clustercount); Rng.fill (Pointchunk, Cv_rand_normal, scalar (center.x, center.y), scalar (img.cols*0.05, img.rows*0.05)); } randshuffle (Points,1, &rng); Kmeans (points, Clustercount, labels, termcriteria (Cv_termcrit_eps+cv_termcrit_iter,Ten,1.0),3, Kmeans_pp_centers, CENTERS); img = Scalar::all (0); for(i =0; i < Samplecount; i++) {intClusteridx = labels.at<int> (i); Point IPT = points.at<point2f> (i); Circle (IMG, IPT,2, Colortab[clusteridx], cv_filled, CV_AA); } imshow ("Clusters", IMG);CharKey = (Char) Waitkey ();if(Key = = -|| Key = =' Q '|| Key = =' Q ') Break; }return 0;}
This is the generation of random sample points, which are then clustered with K-means.
Code is relatively simple, if you have questions Welcome to Exchange ~
Resources:
1, Visual machine learning 20 speak
2. OpenCV Learning Routines (under the source folder of the OpenCV installation path)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
K-means algorithm matlab and OPENCV code