使用 matlab 數字影象處理(三)—— 實現影象的旋轉(不使用 imrotate)
阿新 • • 發佈:2018-12-30
影象的旋轉是不改變影象的灰度值的,這是將原始位置對映到新的位置。
Image = imread('pout.tif');
[X,Y]=size(Image);
imshow(Image);
Angle = pi/6;
%計算四個角點的新座標,確定旋轉後的顯示區域
LeftTop(1,1)=-(Y-1)*sin(Angle);
LeftTop(1,2)=(Y-1)*cos(Angle);
LeftBottom(1,1)=0;
LeftBottom(1,2)=0;
RightTop(1,1 )=(X-1)*cos(Angle)-(Y-1)*sin(Angle);
RightTop(1,2)=(X-1)*sin(Angle)+(Y-1)*cos(Angle);
RightBottom(1,1)=(X-1)*cos(Angle);
RightBottom(1,2)=(X-1)*sin(Angle);
%計算顯示區域的行列數
Xnew=max([LeftTop(1,1),LeftBottom(1,1),RightTop(1,1),RightBottom(1,1)])-min([LeftTop(1,1),LeftBottom(1,1),RightTop(1,1),RightBottom(1 ,1)]);
Ynew=max([LeftTop(1,2),LeftBottom(1,2),RightTop(1,2),RightBottom(1,2)])-min([LeftTop(1,2),LeftBottom(1,2),RightTop(1,2),RightBottom(1,2)]);
% 分配新顯示區域矩陣
ImageNew=zeros(round(Xnew),round(Ynew));
%計算原影象各畫素的新座標
for indexX=0:(X-1)
for indexY=0:(Y-1)
ImageNew(round(indexX*cos(Angle)-indexY*sin (Angle))+ ...
round(abs(min([LeftTop(1,1),LeftBottom(1,1),
RightTop(1,1),RightBottom(1,1)])))+1,1+round(indexX*sin(Angle)+indexY*cos(Angle))+round(abs(min([LeftTop(1,2),LeftBottom(1,2),RightTop(1,2),RightBottom(1,2)]))))=Image(indexX+1,indexY+1);
end
end
h=(ImageNew)/255;
h=medfilt2(h);
figure,imshow(h)
imwrite(h,'rotate.jpg','quality',100);