Thursday 5 April 2018

KNN For Images In MATLAB

clc;
clear all;
I1= im2double(imread('E:\band\band1.gif'));
I2= im2double(imread('E:\band\band2.gif'));
I3= im2double(imread('E:\band\band3.gif'));
I4= im2double(imread('E:\band\band4.gif'));

fileID = fopen('dp1.txt','r');
formatSpec = '%i';
A = fscanf(fileID,formatSpec);
mat1=zeros(50,1);
A=A';
 c=1;
 for j=1:50
      mat1(j,1)=I1(A(c),A(c+50));
      mat1(j,2)=I2(A(c),A(c+50));
      mat1(j,3)=I3(A(c),A(c+50));
      mat1(j,4)=I4(A(c),A(c+50));
      c=c+1;
 end
fileID2 = fopen('dp2.txt','r');
formatSpec2 = '%i';
B = fscanf(fileID2,formatSpec2);
B=B';
 mat2=zeros(100,1);

c=1;
for j=101:150
     mat1(j,1)=I1(B(c),B(c+100));
     mat1(j,2)=I2(B(c),B(c+100));
     mat1(j,3)=I3(B(c),B(c+100));
     mat1(j,4)=I4(B(c),B(c+100));
     c=c+1;
end
k=9;
for i=1:512
    for j = 1:512
        for l = 1:150
        distr(k) = norm([I1(i,j),I2(i,j),I3(i,j),I4(i,j)] - [mat1(l,1),mat1(l,2),mat1(l,3),mat1(l,4)]);
        k=k+1;
        end
        k=1;
        [ans,index] = sort(distr);
        if(index(1) <=50)
            I1(i,j) = 255;
        else
            I1(i,j) = 0;
        end
    end
end

imshow(I1);

No comments:

Post a Comment