MATLAB Answers

image processing, k nearest neighbor

67 views (last 30 days)
Ahsen Feyza Dogan
Ahsen Feyza Dogan on 12 Jul 2019
Commented: KSSV on 12 Jul 2019
Hi, I am trying to make image classification with knn but I stuck in how can I compare selected paint and neighbor pixel value. Thank you
clc;
clear all;
a=imread('coins.png');
b=im2bw(a);
imshow(b);
c=zeros(size(b));
[ptx,pty] = ginput(1);
newdata=[ptx, pty];
[nx,ny] = size(b);
[X,Y] = meshgrid(1:nx,1:ny) ;
ed=sqrt(((newdata(1)-X).^2)+((newdata(2)-Y).^2));
dist=ed(:);
neighbor = mink(dist,400);
num=0;
threshold=201;
ind = ismember(dist, neighbor);
% Extract the elements of a at those indexes.
%num=0;
label=0;
% %find index of neighbor in euc then obtain label
indexes = find(dist);
for i=1:neighbor
if b(indexes(i))==1
num=num+1;
if num>=threshold
label=1;
else
label=3;
end
end
end

  0 Comments

Sign in to comment.

Answers (1)

KSSV
KSSV on 12 Jul 2019
This is how you can use knnsearch.
a=imread('coins.png');
b=im2bw(a);
c=zeros(size(b));
[ptx,pty] = ginput(1);
newdata=[ptx, pty];
[nx,ny] = size(b);
[X,Y] = meshgrid(1:nx,1:ny) ;
ed=sqrt(((newdata(1)-X).^2)+((newdata(2)-Y).^2));
n = 10 ; % number of neighbor points needed
idx = knnsearch([X(:),Y(:)],[ptx pty],'k',n) ;
imshow(b);
hold on
plot(X(idx),Y(idx),'*r')
plot(ptx,pty,'*g')

  2 Comments

KSSV
KSSV on 12 Jul 2019
Ahsen Feyza Dogan commented: Thank you. How can I compare pixel value of this neighbors and picked data?
KSSV
KSSV on 12 Jul 2019
knnsearch gives you the indices of the neighboring points to a given point. If idx are the indicesm then the pixels for the given points are I(idx).
PS: 1. If you are asking a question for a given answer, don't type it as a answer, continue the discussion in the answer.
2. You have asked a previous question and not closed the question. Please close the previous questions, give acknowledgement to the people who answered you and ask next question.

Sign in to comment.

Sign in to answer this question.