0
votes

I have plotted a bounding box over an image:

bbox = [50 20 200 50];
figure; imshow('coins.png'); 
hold on; 
rectangle('Position', bbox, 'EdgeColor','r', 'LineWidth', 3);
hold off;

How can I rotate the bounding box bbox by 30 degrees around the centroid and then obtain the coordinates of the new box, so I can use it with inpolygon?

Update: Please use a bounding box defined as [x y width height].

1
rotate it around what axis? do you want to rotate it with respect to the origin (0,0)? the center of the box (150,45)? the corner of the box? - Shai
Thanks, I will try your answer out. - Chris Parry

1 Answers

2
votes

To rotate the coordinates of the bounding box you only need to define the proper rotation matrix.

Start with defining the coordinates of the four corners:

X = [bbox(1), bbox(1), bbox(1)+bbox(3), bbox(1)+bbox(3), bbox(1)];
Y = [bbox(2), bbox(2)+bbox(4), bbox(2)+bbox(4), bbox(2), bbox(2)];

Rotation always rotates around the origin (0,0), if you want to rotate around the center of the box you need to adjust X and Y before and after the rotation

Cx = bbox(1)+0.5*bbox(3);
Cy = bbox(2)+0.5*bbox(4);

Rotating

Xr = X-Xc; %// subtract center
Yr = Y-Cy;
Xr = cosd(30)*Xr-sind(30)*Yr; %// rotate
Yr = sind(30)*Xr+cosd(30)*Yr;
Xr = Xr+Xc; %// add center back
Yr = Yr+Yc;

Now you can plot the rotated box

plot( Xr, Yr );

You can use Xr and Yr as xv and yv arguments for inpolygon.


All these algebraic manipulations can be done more elegantly using homogeneous coordinates, that allows the translation (subtracting/adding the center of the rect) to be expressed as a matrix multiplication.

H = [X;Y;ones(1,5)]; %// points as 3D homogeneous coordinates
Tc = [1 0 -Cx; 0 1 -Cy; 0 0 1]; %// translation as a matrix
Tr = [cosd(30) -sind(30) 0; sind(30) cosd(30) 0; 0 0 1]; %// rotation
Hr = inv(Tc) * Tr * Tc * H; %// all transformations as matrix products

plot( Hr(1,:), Hr(2,:) ); %// the rotated rect