MATLAB Answers


reading and Image and classifying This using KNN stages

Asked by Matpar
on 26 Sep 2019
Latest activity Commented on by Matpar
on 2 Oct 2019
Hi Professionals,
I would love it very much if someone can guide me on the processes of reading a single image and classifying objects on it
using KNN in matlab!
I am not sure of the processes or the where to start hence I am requesting assistance kindly!
Please note I have no code nor the understanding of the stages or the steps that is required to use KNN.
My first step
step 1 read the image into matlab
Step 2 "I am not sure what to do next (Googling the life out of Google! Still Confused)"
please guide me!
Let me thank you in advance for acknowledging me and my request, I appreacite this loads on my quest to learn!
Thank you loads!


Hi KA! Thanks for responding! So i went over to the e.g. but it's in python! Is there a method available in matlab!
I really got the gist of the variations between K means and knn
Can KNN be done for a single image? if yes, what is the steps to do this in MATLAB?
Thank you for acknowledging me and responding in advance!!

Sign in to comment.

1 Answer

Answer by Dheeraj Singh on 30 Sep 2019
Edited by Dheeraj Singh on 30 Sep 2019
 Accepted Answer

To answer your question first we need to understand what KNN is and how it works.
KNN stands for K-nearest neighbors, which is a classification technique.
  • Given a sample of images and their classes already known,
  • We can take an image as input and find the k-nearest neighbors to the input image
  • The k-nearest neighbors are found out based on a ‘distance’ metric which can be changed depending upon the data.
  • k can also be changed
  • Now depending upon the k-nearest neighbors, we classify the input image.
Now to answer your question: Can KNN be done for a single image
Yes, we can use KNN for a single image if we already have the dataset of sample images for different classes.
If we only have one image and nothing else, then we cannot use KNN.
Please go through the documentation of knn to know more.


This was my example or the KNN (but this is wrong) I am trying to do this from scratch to understand the various stages of how to do the KNN classification
im = imread('car.jpg'); % Read in the source image
figure; imshow(im);
[r,c,s]=size(im); %initialise r,c,s as the size of (im)
% im is a RGB image therefore im will be 3 dimensional
%initialise the storage variables for each sample region
numberofClasses=length(classes); %The Number of The Classes Would be 7 Colours
sample_regions = false([r c numberofClasses]); %initialise a matrics for sample regions not that it is all equal to zeros denoted by the syntax
%Step 1 Selecting the sample regions
figim = figure;
for count=1:numberofClasses % Selecting the sample regions for every 7 class that was created
set(figim,'name',['Please Select The Sample Region For ' classes{count}]);
%Step 2 After selecting the sample regions it is displayed via the loop
%iterate through all the classes to show all sample regions initialised
for count=1:numberofClasses
title(['The Sample Region For' classes{count}]);
%Convert RGB image to L*a*B image
%LaB format give an L which is the U value as well as A & B channels
%This will assist with identifying the labels for the new pixles being
%(makecform) is an inbuilt funtion which make a transform from colour names
%to the colour space cordinate system and this is then Converted from
%srgb2lab (Standard Computer Monitor Vlaues and it is converted by the LaB
cform = makecform('srgb2lab');
lab_im=applycform(im,cform); %Apply the conversionform transformation onto the image that was read(im)
% Once the L*a*B Values were calculate The (MEAN) for the (a*) and (*b)
% values for each Region Of Interests (ROI) areas
color_markers= zeros([numberofClasses, 2]); %This matrix will highlight the values
%of the (MEAN of the a & b varibles for all of the 7 classes that was selected)
for count=1:numberofClasses
color_markers(count,1)=mean2(a(sample_regions(:,:,count))); %This presents the mean for a of every colour class created
color_markers(count,2)=mean2(b(sample_regions(:,:,count))); %This presents the mean for b of every colour class created
%Step 3 Classify Each Pixel Using The kNearest Neighbour Rule
% Each colour maeker has a* & b* values, Each pixle can be classified in
% the Lab_im image by calculating the Euclidean Distance between the pixel
% and each colour marker
% The Smallest Distance highlights the pixel that closely matches that
% colour marker.
%EG if the distance between the grey and a pixel is the smallest then that
%pixel is labeled grey
color_labels=0:numberofClasses-1; % First initialise colour lables starting from zero, one till five
a=double(a); %converted as a double to perform mathematical operations on these
b=double(b); %converted as a double to perform mathematical operations on these
distance=repmat(0, [size(a), numberofClasses]); %initialise a distance matrix to find out each and every pixel from the colour markers
%Performing the Classifiation
for count=1:numberofClasses %iterating from 1 through the 7 classes
%obtaining the Euclidean distance of each and every pixel from the colour marker
[value, label]=min(distance,[],3); %assigning the value and the lable as the minimum of the distance
label=color_labels(label); %The Label here is sorted and assigned to the particular pixel specified as the minimum distance
%Colours='Navy Blue','White'
colors=[0.1686 0.2235 1.0000; 1 1 1];
for m=1:r
for n=1:c
figure; imshow(y)
% Scatter plot for the nearest neighbour classification
purple = [119/255 73/255 152/255]; %from left red, green, blue, define a new purple color
plot_labels = {'k',purple, 'm'}; %defining the plot labels black red green purple magenta and yellow
hold on
%plotting the values utilising the standard plot parameters
for count=1:numberofClasses
plot(a(label==count-1),b(label==count-1), '.','MarkerEdgeColor', plot_labels{count}, 'MarkerFaceColor',...
hold on;
title('Scatterplot of the segmented pixels in ''a*b*'' space');
llabel('''a*'' values');
ylabel('''b*'' values'); you want to classify pixels into Background and Foreground.
In this case you can apply KNN on a single image...
Here individual pixels are your data or sample points.
So, when i said you cannot apply knn just on a single image i meant if you are taking an image as one data sample.
But here image is not a data point, the pixels are the data points.
You are selecting an a region of interest for Background and Foreground.
The pixels in the respective regions are your sample points for their respective classes.
Hope this clears your doubt.
yes DS,
that's what my goal is, do you know of an easier way to get this done?
if so please enlighten me for the knowledge!!

Sign in to comment.