Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
KNN segmentation for MATLAB: https://www.youtube.com/watch?v=3hEvcyCJNRc
clear all, close all, clc
%% read the image
x = imread('balls.jpg');
x = imresize(x, 0.3);
figure()
imshow(x)
[r,c,s] = size(x);
%% Initialize storage for each sample region
classes = {'orange','purple','green','background'};
nClasses = length(classes);
sample_regions = false([r c nClasses]);
%% Select each sample region
f = figure;
for count = 1:nClasses
set(f, 'name', ['Select sample region for ' classes{count}]);
sample_regions(:,:,count) = roipoly(x);
end
close(f);
%% Display sample regions
for count = 1:nClasses
figure
imshow(sample_regions(:,:,count))
title(['sample region for ' classes{count}]);
end
%% Convert to L*a*b
cform = makecform('srgb2lab');
lab_x = applycform(x,cform);
figure()
imshow(lab_x)
%% Calculate the mean 'a*' and 'b*' value for each ROI area
a = lab_x(:,:,2);
b = lab_x(:,:,3);
color_markers = repmat(0, [nClasses, 2]);
for count = 1:nClasses
color_markers(count,1) = mean(a(sample_regions(:,:,count)));
color_markers(count,2) = mean(b(sample_regions(:,:,count)));
end
%% Classify each pixel using the nearest neighbor rule
color_labels = 0:nClasses-1;
a = double(a);
b = double(b);
distance = repmat(0, [size(a), nClasses]);
%% Perform classification
for count = 1:nClasses
distance(:,:,count) = ((a - color_markers(count,1)).^2 + ...
(b - color_markers(count,2)).^2);
end
[value, label] = min(distance,[],3); % as label it return the index,, in our case it is count
label = color_labels(label); % Makes it from 0 to 3 instead of from 1 to 4
%% clear value distance
% colors = [255 0 0; 0 255 0; 0 0 255; 255 255 0; 255 0 255; 0 255 255]; % R G B R-G R-B G-B
colors = [255 0 0; 0 255 0; 0 0 255; 255 255 0]; % R G B R-G(Yellow) Same number as classes in the picture
y = zeros(size(x));
l = double(label) + 1;
for m = 1:r
for n = 1:c
y(m,n,:) = colors(l(m,n),:);
end
end
figure()
imshow(y)
colorbar
%% Scatter plot for the nearest neighbour classification
purple = [119/255 73/255 152/255];
plot_labels = {'k', 'r', 'g', purple};
figure()
for count = 1:nClasses
plot(a(label == count-1), b(label == count-1),'.','MarkerEdgeColor',...
plot_labels{count}, 'MarkerFaceColor', plot_labels{count});
hold on
end
title('Scatterplot of the segmented pixels in ''a*b*'' space');
xlabel('''a*'' values');
ylabel('''b*'' values');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.