如何在matlab中围绕物体中心旋转图像?

How to rotate image around the center of object in matlab?

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

例如二进制掩码中的斑点中心。如果使用 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');

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

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

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

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

例如,要像您的示例中那样旋转 -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);