如何在matlab中围绕对象中心旋转图像?

时间:2018-05-26 10:49:28

标签: matlab image-processing image-rotation

matlab中的imrotate函数围绕中心旋转图像。如何通过自定义坐标旋转图像?

例如二进制掩码中的blob中心。如果使用imcrop并将blob放在中心,如何将其重塑为原始图像?

代码

% create binary mask 
clc; 
clear;
mask= zeros(400,600,'logical'); 
positein = [280,480];
L = 40;
x = positein (1);
y = positein (2);
mask(x,y-L:y+L) = 1;
for i =1:8
mask(x+i,y-L:y+L) = 1;
mask(x-i,y-L:y+L) = 1;
end
Angle = 45;
mask_after_rotation = imrotate(mask,-Angle,'crop');
figure,
subplot(1,2,1),imshow(mask),title('before rotation');
subplot(1,2,2),imshow(mask_after_rotation),title('after rotate 45');

2 个答案:

答案 0 :(得分:1)

这通常是通过构造仿射变换来执行的,仿射变换将我们想要旋转的点转换为原点,然后执行旋转,然后进行平移。

例如,要像您的示例一样旋转-45度,我们可以执行以下操作

% create binary mask
mask = zeros(400, 600,'logical'); 
positein = [480, 200];
W = 40; H = 8;
x = positein(1); y = positein(2);
mask(y-H:y+H, x-W:x+W) = 1;

angle = -45;

% translate by -positein, rotate by angle, then translate back by pt
T = [1 0 0; 0 1 0; -positein 1];
R = [cosd(angle) -sind(angle) 0; sind(angle) cosd(angle) 0; 0 0 1];
Tinv = [1 0 0; 0 1 0; positein 1];
tform = affine2d(T*R*Tinv);
mask_rotated = imwarp(mask, tform, 'OutputView', imref2d(size(mask)));

figure(1); clf(1);
subplot(1,2,1),imshow(mask),title('before rotation');
subplot(1,2,2),imshow(mask_rotated),title('after rotate 45');

或者,您可以设置参考对象,使所需坐标位于原点

% Set origin to positein, then rotate
xlimits = 0.5 + [0, size(mask,2)] - positein(1);
ylimits = 0.5 + [0, size(mask,1)] - positein(2);
ref = imref2d(size(mask), xlimits, ylimits);
R = [cosd(angle) -sind(angle) 0; sind(angle) cosd(angle) 0; 0 0 1];
tform = affine2d(R);
mask_rotated = imwarp(mask, ref, tform, 'OutputView', ref);

答案 1 :(得分:0)

您可以进行一系列变换以实现围绕任意点的旋转,其中:1)将任意点移动到图像的中心,2)以预定角度旋转图像,& 3)将其翻译回原始位置。例如,如果要在您的案例中围绕blob的中心旋转蒙版,则可以执行以下步骤。

trns_mask = imtranslate(mask, [-180, -80]);             % Move to the origin
trns_mask_rotated = imrotate(trns_mask,-Angle,'crop');  % Rotate
mask_after_rotation = imtranslate(trns_mask_rotated, [180, 80]);    % Move back

您可以使用options函数imtranslate()来确保在转换过程中不会丢失任何图像信息。