Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Rotate Image By Nearest Neighbor Interpolation Using Matlab

My Plain Code without interpolation:

im1 = imread('lena.jpg');imshow(im1);    
[m,n,p]=size(im1);
thet = rand(1);
m1=m*cos(thet)+n*sin(thet);
n1=m*sin(thet)+n*cos(thet);    

for i=1:m
    for j=1:n
       t = uint16((i-m/2)*cos(thet)-(j-n/2)*sin(thet)+m1/2);
       s = uint16((i-m/2)*sin(thet)+(j-n/2)*cos(thet)+n1/2);
       if t~=0 && s~=0           
        im2(t,s,:)=im1(i,j,:);
       end
    end
end
figure;
imshow(im2);

This code creates black spot, the problem is how to do interpolation? Thank you all for any illumination. P.S. Not asking for build-in function: imrotate(im1,1/thet,'nearest');

like image 532
MeadowMuffins Avatar asked Nov 28 '09 02:11

MeadowMuffins


2 Answers

To rotate the image without the black spots, you need to go in the reverse direction.

The inverse of the rotation matrix is the transpose of it. Also, the rotated image is always bigger with maximum being 45 degree rotation. Hence, the sqrt(2) factor

im1 = imread('lena.jpg');imshow(im1);  
[m,n,p]=size(im1);
thet = rand(1);
mm = m*sqrt(2);
nn = n*sqrt(2);
for t=1:mm
   for s=1:nn
      i = uint16((t-mm/2)*cos(thet)+(s-nn/2)*sin(thet)+m/2);
      j = uint16(-(t-mm/2)*sin(thet)+(s-nn/2)*cos(thet)+n/2);
      if i>0 && j>0 && i<=m && j<=n           
         im2(t,s,:)=im1(i,j,:);
      end
   end
end
figure;
imshow(im2);
like image 100
sjchoi Avatar answered Oct 18 '22 18:10

sjchoi


I remember a previous question on SO that had a similar problem.

The idea I had was to map the pixels in the opposite direction; for each pixel in the rotated image, find the pixel(s) that maps to it in the original image, then the problem becomes much simpler.

I don't have access to MATLAB at this moment, but I think it is doable. The difficulty here is looping over the rotated image pixels..

like image 26
Amro Avatar answered Oct 18 '22 19:10

Amro