% 两维图像旋转以及双线性灰度差值算法的实现
% Ref. 章毓晋. 图像工程(上册)——图像处理. 清华大学出版社
% Author: uestczzk Date: 2010.05.12
im_init = imread('testImg.jpg');
im_init = double(im_init);
im_height = size(im_init,1);
im_width = size(im_init,2);
% 分别处理灰度图像和RGB图像
if ndims(im_init) == 3
im_final = zeros(im_height,im_width,3);
R = im_init(:,:,1);
G = im_init(:,:,2);
B = im_init(:,:,3);
R_final = im_final(:,:,1);
G_final = im_final(:,:,2);
B_final = im_final(:,:,3);
else
im_final = zeros(im_height,im_width);
end
% rot_matrix = input('输入旋转矩阵,大小为2*2');
rot_matrix = [cos(pi/4) -sin(pi/4);sin(pi/4) cos(pi/4)];
for h = 1:im_height
for w = 1:im_width
% 平移至原点,旋转,然后再平移回去
new_position = rot_matrix*[h - im_height/2;w - im_width/2] + [im_height;im_width];
new_position(1) = mod(new_position(1),im_height);
new_position(2) = mod(new_position(2),im_width);
if new_position(1) == 0
new_position(1) = 1;
end
if new_position(2) == 0
new_position(2) = 1;
end
% 如果新位置为整数,那么直接赋予灰度值或者RGB值,否则,按照双线性插值计算,使用后向映射
if new_position == round(new_position)
if ndims(im_init) == 3
R_final(h,w) = R(new_position(1),new_position(2));
G_final(h,w) = G(new_position(1),new_position(2));
B_final(h,w) = B(new_position(1),new_position(2));
else
im_final(h,w) = im_init(new_position(1),new_position(2));
end
else
h_new = floor(new_position(1));
w_new = floor(new_position(2));
if h_new == 0
h_new = 1;
end
if w_new == 0
w_new = 1;
end
if ndims(im_init) == 3
% 双线性插值的实现过程 Ref. 章毓晋. 图像工程(上册)——图像处理. 清华大学出版社
R_temp1 = R(h_new + 1,w_new)*(new_position(1) - h_new) + R(h_new,w_new)*(h_new + 1 - new_position(1));
R_temp2 = R(h_new + 1,w_new + 1)*(new_position(1) - h_new) + R(h_new,w_new + 1)*(h_new + 1 - new_position(1));
R_final(h,w) = R_temp1*(w_new + 1 - new_position(2)) + R_temp2*(new_position(2) - w_new);
G_temp1 = G(h_new + 1,w_new)*(new_position(1) - h_new) + G(h_new,w_new)*(h_new + 1 - new_position(1));
G_temp2 = G(h_new + 1,w_new + 1)*(new_position(1) - h_new) + G(h_new,w_new + 1)*(h_new + 1 - new_position(1));
G_final(h,w) = G_temp1*(w_new + 1 - new_position(2)) + G_temp2*(new_position(2) - w_new);
B_temp1 = B(h_new + 1,w_new)*(new_position(1) - h_new) + B(h_new,w_new)*(h_new + 1 - new_position(1));
B_temp2 = B(h_new + 1,w_new + 1)*(new_position(1) - h_new) + B(h_new,w_new + 1)*(h_new + 1 - new_position(1));
B_final(h,w) = B_temp1*(w_new + 1 - new_position(2)) + B_temp2*(new_position(2) - w_new);
else
gray_temp1 = im_init(h_new + 1,w_new)*(new_position(1) - h_new) + im_init(h_new,w_new)*(h_new + 1 - new_position(1));
gray_temp2 = im_init(h_new + 1,w_new + 1)*(new_position(1) - h_new) + im_init(h_new,w_new + 1)*(h_new + 1 - new_position(1));
im_final(h,w) = gray_temp1*(w_new + 1 - new_position(2)) + gray_temp2*(new_position(2) - w_new);
end
end
end
end
if ndims(im_init) == 3
im_final(:,:,1) = R_final;
im_final(:,:,2) = G_final;
im_final(:,:,3) = B_final;
else
im_final = im2uint8(mat2gray(im_final));
end
figure(1)
imshow(im2uint8(mat2gray(im_init)));
title('原始图像')
figure(2)
imshow(uint8(im_final))
title('旋转图像')