-
Notifications
You must be signed in to change notification settings - Fork 7
/
SegmentImage.m
46 lines (39 loc) · 1.76 KB
/
SegmentImage.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
% Function to call and evaluate features
function [seg_img] = SegmentImage(I,k_val)
% Color Image Segmentation
% Use of K Means clustering for segmentation
% Convert Image from RGB Color Space to L*a*b* Color Space
% The L*a*b* space consists of a luminosity layer 'L*', chromaticity-layer 'a*' and 'b*'.
% All of the color information is in the 'a*' and 'b*' layers.
cform = makecform('srgb2lab');
% Apply the colorform
lab_he = applycform(I,cform);
% Classify the colors in a*b* colorspace using K means clustering.
% Since the image has 3 colors create 3 clusters.
% Measure the distance using Euclidean Distance Metric.
ab = double(lab_he(:,:,2:3));
nrows = size(ab,1);
ncols = size(ab,2);
ab = reshape(ab,nrows*ncols,2);
nColors = 3;
[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ...
'Replicates',k_val);
%[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','Replicates',3);
% Label every pixel in tha image using results from K means
pixel_labels = reshape(cluster_idx,nrows,ncols);
%figure,imshow(pixel_labels,[]), title('Image Labeled by Cluster Index');
% Create a blank cell array to store the results of clustering
segmented_images = cell(1,k_val);
% Create RGB label using pixel_labels
rgb_label = repmat(pixel_labels,[1,1,3]);
for k = 1:nColors
colors = I;
colors(rgb_label ~= k) = 0;
segmented_images{k} = colors;
end
%figure, subplot(2,1,1);imshow(segmented_images{1});title('Cluster 1'); subplot(2,1,2);imshow(segmented_images{2});title('Cluster 2');
%subplot(3,1,3);imshow(segmented_images{3});title('Cluster 3');
mean_cluster_value = mean(cluster_center,2);
[~, idx] = max(mean_cluster_value);
seg_img = segmented_images{idx};
%imshow(seg_img), title('Segmented image');