22% Apply k-means clustering to a multi-channel image.
33%
44% CLASSES = kmeans(IMG, K)
5- % Compute kmeans clustering of the multi-channel image IMG, using K
6- % classes .
5+ % Compute kmeans clustering of the image IMG, using K classes. The result
6+ % is a label image with values ranging from 1 no K .
77%
88% [CLASSES, CENTERS] = kmeans(IMG, K);
99% Also returns the coordinates of class centers. CENTERS is a K-by-NC
1010% array, where NC is the number of channels of original image IMG.
1111%
12+ % Requires the statistics toolbox.
1213%
1314% Example
15+ % % k-means segmentation of a RGB color image
1416% img = Image.read('peppers.png');
1517% cls = kmeans(img, 6);
1618% % display the classes with arbitrary colors
2224% rgb = label2rgb(cls, map);
2325% figure; show(rgb);
2426%
27+ % % multi-level segmentation of a grayscale image with k-means
28+ % nc = 5;
29+ % img = Image.read('cameraman.tif');
30+ % [classes, values] = kmeans(img, nc);
31+ % res = Image.zeros(size(img),'uint8');
32+ % for i = 1:nc
33+ % res(classes == i) = values(i);
34+ % end
35+ % figure; show(res);
36+ %
2537% See also
2638% label2rgb, fold
2739%
3345% Created: 2020-01-15, using Matlab 9.7.0.1247435 (R2019b) Update 2
3446% Copyright 2020 INRAE.
3547
36- if channelNumber(obj ) < 2
37- error(' Requires a multi-channel image' );
38- end
39-
4048% convert image content into nr-by-nc array
41- nr = elementNumber (obj );
42- nc = channelNumber (obj );
49+ nr = elementCount (obj );
50+ nc = channelCount (obj );
4351data = double(reshape(obj .Data , [nr nc ]));
4452
4553% run the kmeans algorithm
54+ % (use statistics toolbox function)
4655[idx , centers ] = kmeans(data , k );
4756
4857% convert to label image, by avoiding zero label
4958idx = reshape(idx , size(obj ));
5059
5160% create parent image
52- newName = ' classes' ;
53- if ~isempty(obj .Name )
54- newName = sprintf(' %s -kmeans%d ' , obj .Name , k );
55- end
56- res = Image(' Data' , idx , ' Type' , ' label' , ...
57- ' parent' , obj , ' Name' , newName , ...
58- ' ChannelNames' , {' Class' });
61+ newName = createNewName(obj , sprintf(' %% s-kmeans%d ' , k ));
62+ res = Image(' Data' , idx , ' Parent' , obj , ...
63+ ' Type' , ' label' , ' Name' , newName , ...
64+ ' ChannelNames' , {' Class' });
0 commit comments