image processing, k nearest neighbor

21 views (last 30 days)
Ahsen Feyza Dogan
Ahsen Feyza Dogan on 12 Jul 2019
Answered: Image Analyst on 10 Apr 2023
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

Answers (2)

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')
  3 Comments
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.
oscillator
oscillator on 10 Apr 2023
I don't understand why u use ginput(1). Can it be avoided?

Sign in to comment.


Image Analyst
Image Analyst on 10 Apr 2023
Here's simple demo, attached, that operates on (x,y) data.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!