figure_rotate.m

来自「MATLAB环境下任意角度的图像旋转算法」· M 代码 · 共 102 行

M
102
字号
%get the matrix of the primitive image
a=imread('d:\pictures\fbbb8863da45c6b0eaf467855d4db44d.jpg');

%get the size of the image matrix
[M,N,K]=size(a);

%get the rotate angle
ang=57;

%put the rotate angle into the suitable XIANGXIAN
if ang>360
    ang=ang-(floor(ang/360))*360;
end

if ang<=90
    phi=ang*pi/180;
    sit=1;
else if ang>90&&ang<=180
        phi=(ang-90)*pi/180;
        sit=2;
    else if ang>180&&ang<=270
            phi=(ang-180)*pi/180;
            sit=3;
        else if ang>270&&ang<=360
                phi=(ang-270)*pi/180;
                sit=4;
            end
        end
    end
end

H=[1 1 1 1;M 1 M 1;1 N N 1;M N M*N 1];

%calculate the length and width of the recepient matrix
switch sit
    case 1 
        MM=ceil(M*cos(phi)+N*sin(phi));
        NN=ceil(M*sin(phi)+N*cos(phi));
        h1=[N*sin(phi);MM;1;M*cos(phi)];
        h2=[1;M*sin(phi);N*cos(phi);NN];
    case 2 
        MM=ceil(M*sin(phi)+N*cos(phi));
        NN=ceil(M*cos(phi)+N*sin(phi));
        h1=[MM;N*cos(phi);M*sin(phi);1];
        h2=[N*sin(phi);NN;1;M*cos(phi)];
    case 3
        MM=ceil(M*cos(phi)+N*sin(phi));
        NN=ceil(M*sin(phi)+N*cos(phi));
        h1=[M*cos(phi);1;MM;N*sin(phi)];
        h2=[NN;N*cos(phi);M*sin(phi);1]
    case 4
        MM=ceil(M*sin(phi)+N*cos(phi));
        NN=ceil(M*cos(phi)+N*sin(phi));
        h1=[1;M*sin(phi);N*cos(phi);MM];
        h2=[M*cos(phi);1;NN;N*sin(phi)];
end

X=inv(H)*h1;
Y=inv(H)*h2;

%initialize the recepient matrix
b=zeros(MM,NN,K,'uint8');
c=zeros(MM,NN,K,'uint8');

%shift the pixel to the suitable place and interpolate suitable value into 
%the ones that need to be 
for k=1:K
    for i=1:M
        for j=1:N
            ii=[i,j,i*j,1]*X;
            if ii-floor(ii)<=0.5
                ii=int32(floor(ii));
            else ii=int32(ceil(ii));
            end
            if ii<=int32(0)
                ii=int32(1);
            end
            jj=[i,j,i*j,1]*Y;
            if jj-floor(jj)<=0.5
                jj=int32(floor(jj));
            else jj=int32(ceil(jj));
            end
            if jj<=int32(0)
                jj=int32(1);
            end
            b(ii,jj,k)=a(i,j,k);
            for e=0:1
                for f=0:1
                    if ii+e<=MM&&ii-e>=int32(0)&&jj+f<=NN&&jj-f>=int32(0)
                        if b(ii+e,jj+f,k)==int32(0)
                            b(ii+e,jj+f,k)=b(ii,jj,k);
                        end
                    end
                end
            end
        end
    end
end

%show the image
imshow(b);
        

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?