mbghr
mbghr

Reputation: 3

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

Upvotes: 0

Views: 1560

Answers (2)

jodag
jodag

Reputation: 22204

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

Upvotes: 1

Nakini
Nakini

Reputation: 772

You could do a series of transformation to achieve the rotation around an arbitrary point, which are: 1) Move the arbitrary point to the center of the image, 2) Rotate the image by a predefined angle, & 3) Translate it back to the original position. For example, if you want to rotate the mask around the center of the blob in your case, then you could carry out the following steps.

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

There are options for the function imtranslate() which you could play with to make sure you are not losing any image information during the transformation.

Upvotes: 0

Related Questions