matlab实现:
使用函数imrotate,调用格式为:B = imrotate(A,angle);B=imrotate(A,angle,method);B=imrotate(A,angle,method,bbox);
其中,A:输入图像;angle:角度,正数表示逆时针;method:插值算法,有‘nearest’,'bilinear','bicubic';bbox:指定输出图像的属性,‘crop’对输出图像进行剪裁,‘loose’是输出图像足够大;
具体实现原理:
首先需要确定四个角的坐标,然后声明平移矩阵,旋转矩阵,随后根据旋转矩阵和平移矩阵算出旋转后四个角的坐标,得到四个角的坐标后我们就能算出旋转后图像的长宽,随后写一个二重循环算所有点平移后的坐标,算出的坐标可能会是小数,所以需要进行插值处理。具体原理详见http://blog.youkuaiyun.com/liyuan02/article/details/6750828;
img = imread('F:/timg.jpg');
[x,y] = size(img);
%四个角的坐标
horn = [0,0,x-1,x-1;0,y-1,y-1,0];
%平移矩阵
tran = [x/2,x/2,x/2,x/2;y/2,y/2,y/2,y/2];
%旋转角度
angle = 2*pi/3;
%算三角函数值
cs = cos(angle);
sn = sin(angle);
%旋转矩阵
rotate = [cs,-sn;sn,cs];
%旋转后四个角的坐标
newhorn = rotate*(horn-tran)+tran;
%新图像的长宽
newX = round(max(newhorn(1,:))-min(newhorn(1,:)));
newY = round(max(newhorn(2,:))-min(newhorn(2,:)));
%初始化矩阵
newImg = zeros(newX,newY);
%坐标轴平移情况
tranX = newX - x;
tranY = newY - y;
%计算每个点的坐标
for indexX = 1:x
for indexY = 1:y
x0 = ceil((indexX-x/2)*cs - (indexY-y/2)*sn + x/2 + tranX/2+1);
y0 = ceil((indexX-x/2)*sn + (indexY-y/2)*cs + y/2 + tranY/2+1);
newImg(x0,y0)=img(indexX,indexY);
end
end
figure;
imshow(medfilt2(newImg/255));
figure;
imshow(img);