-
Notifications
You must be signed in to change notification settings - Fork 0
/
kMeansRgb.m
47 lines (32 loc) · 1.24 KB
/
kMeansRgb.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
%% k-Means
% Define the k parameter which is number of classes in the image (clusters).
kClasses = 8;
[colsRGB, linesRGB, channels] = size(higResRgb);
% Unfold the datacube with samples on rows and spectral data on columns.
kInputRGB = zeros(colsRGB * lines, channels);
for i = 1:colsRGB
for j = 1:linesRGB
kInputRGB(((i - 1) * linesRGB + j), :) = higResRgb(i, j, :);
end
end
[idx, C] = kmeans(kInputRGB, kClasses);
%%
lab_he = rgb2lab(higResRgb);
ab = lab_he(:,:,2:3);
ab = im2single(ab);
nColors = 8;
% repeat the clustering 3 times to avoid local minima
pixel_labels = imsegkmeans(ab,nColors,'NumAttempts',3);
imshow(pixel_labels,[])
title('Image Labeled by Cluster Index');
%% Display classification result.
% usedClassList = [3, 4, 5, 7, 8, 9, 10, 13];
classifiedImage = zeros(cols, lines, channels, 'uint8');
for n = 1: length(idx)
row = fix(n/linesRGB) + 1;
column = mod(n,linesRGB) + 1;
classifiedImage(row, column, :) = Get_Label_Color(idx(n));
end
clear colsRGB linesRGB row column kInputRGB kClasses;
figure()
imshow(classifiedImage)