whats wrong with this code? i wanna zoom 2D image using nearest neighbor interpolation

2 views (last 30 days)
function nearest_neighbor_zoom(file,fac)
im=imread(file);
[h,v,d]=size(im);
for i=1:h
for j=1:v
im1( floor(1+(i-1)*fac), floor(1+(j-1)*fac),:)=im(i,j,:); %mapping pixels of given image to a new array so that zooming factor is satisfied.
end
end
[h1,v1,d]=size(im1);
disp('Unknown pixel values are being interpolated. Look at Figure1');
%nearest neighbor interpolation
for i=1:h1-1
for j=1:v1-1
if( (floor( 1+( ceil((i-1)/fac+1) -1)*fac )==i) && ( floor( 1+( ceil((j-1)/fac+1) -1)*fac )==j ) ) % maped values from the original picture should not be recalculated.
else %for pixels that should be calculated
if(floor( 1+( ceil((i-1)/fac+1) -1)*fac )==i) %on a defined vertical level
xo00=ceil((i-1)/fac+1);
x00=i;
else
xo00=floor((i-1)/fac+1);
x00=floor(1+(xo00-1)*fac);
end
if( floor( 1+( ceil((j-1)/fac+1) -1)*fac )==j )%on a defined horizontal level
yo00=ceil((j-1)/fac+1);
y00=j;
else
yo00=floor((j-1)/fac+1);
y00=floor(1+(yo00-1)*fac);
end
xo10=xo00+1;
yo10=yo00;
x10=floor(1+(xo10-1)*fac); %current coordinate of 10;
y10=floor(1+(yo10-1)*fac);
xo01=xo00;
yo01=yo00+1;
x01=floor(1+(xo01-1)*fac); %current coordinate of 01;
y01=floor(1+(yo01-1)*fac);
xo11=xo10;
yo11=yo01;
x11=x10; %current coordinate of 11;
y11=y01;
xlen=x11-x00;
ylen=y11-y00;
x=i-x00;
y=j-y00;
dx=x/xlen; %converting coordinates of the pixel being calculated to (0*1)(0*1) domain.
dy=y/ylen;
if dx<=0.5 %if the pixel being calculated is near to the known upper pixel level.
nx=0;
else %to known lower pixel level.
nx=1;
end
if dy<=0.5 %if the pixel being calculated is near to the known left pixel level.
ny=0;
else %to known right pixel level.
ny=1;
end
if ((nx==0) &&(ny==0)) %assigning the upper left known pixel to the pixel being calculated.
h00=im1(x00,y00,:);
im1(i,j,:)=h00;
elseif ((nx==1) && (ny==0)) %assigning the lower left known pixel to the pixel being calculated.
h10=im1(x10,y10,:);
im1(i,j,:)=h10;
elseif((nx==0) && (ny==1)) %assigning the upper right known pixel to the pixel being calculated.
h01=im1( x01,y01,:);
im1(i,j,:)=h01;
elseif((nx==1)&&(ny==1)) %assigning the lower right known pixel to the pixel being calculated.
h11=im1(x11,y11,:);
im1(i,j,:)=h11;
end
end
end
imshow(im1); %displaying image being interpolated.
end
disp('Zooming is complet. Look at Figure1');
imshow(im1);
imwrite(im1,'zoomed_pic.jpg');

Accepted Answer

madhan ravi
madhan ravi on 27 Oct 2018
Edited: madhan ravi on 27 Oct 2018
file is the name of the file , you should call the function as such because your function requires two inputs , you can't simply press the green button to run without inputs defined
file ='example.jpg' %example
fac = 4 %example
function nearest_neighbor_zoom(file,fac)
  11 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!