【问题标题】:How to rotate image around the center of object in matlab?如何在matlab中围绕对象中心旋转图像?
【发布时间】:2018-05-26 10:49:28
【问题描述】:

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');

【问题讨论】:

    标签: matlab image-processing image-rotation


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      您可以进行一系列变换来实现围绕任意点的旋转,它们是: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(),您可以使用它来确保在转换过程中不会丢失任何图像信息。

      【讨论】:

      • @mbghr,imtranslate 的输入参数是 xy 而不是 row。因此,在移动时,x 轴需要 -180 (= 600/2 - 480),y 轴需要 -80 (= 400/2 - 280)。
      猜你喜欢
      • 2018-04-26
      • 1970-01-01
      • 2017-02-06
      • 2014-05-19
      • 2011-07-08
      • 2016-09-10
      • 2020-05-19
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多