Search code examples
matlabimage-processingimage-rotation

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


imrotate function in matlab rotates the image around the center. How to rotate image by custom coordinates?

For example center of blob in binary mask. If using imcrop and place blob in the center, how to reshape that to same as original image?

Code

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

Solution

  • This is generally performed by constructing an affine transform which translates the point about which we want to rotate to the origin, then performs a rotation, then translates back.

    For example, to rotate by -45 degrees like in your example we could do the following

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

    Alternatively you can set the reference object so that the desired coordinate is at the origin

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