# How to get pixel location in after rotating the image?

I'm trying to rotate some images with some boundary boxes, but I couldn't get the new bb. So if I have an image of 100x70 and I have a pixel at (19,39) and then I rotate the image with angle = 45, how can I calculate the new position of this pixel?

• EDIT: As pointed out by Frank, the original answer mixed up row vector and column vector affine transformations. The formulas have been edited to use row vectors to be consistent with the referenced Mathworks page.

You first need to define where you are rotating your image around.

If you are rotating it around (0,0) (i.e. your image is located in the positive x and y quadrant), you can apply a rotation matrix in its vanilla form:

$$\left[\begin{array}{c}x' \\y' \\1\end{array}\right]^T=$$ $$\left[\begin{array}{c}x \\y \\1\end{array}\right]^T \begin{bmatrix}\cos \theta &\sin \theta &0\\-\sin \theta & \cos \theta &0 \\0 &0 &1\end{bmatrix}$$=$$\left[\begin{array}{c}x\cos\theta + y\sin\theta \\-x\sin\theta+y\cos\theta \\1\end{array}\right]^T$$

where x and y is your starting pixel location, x' and y' is your new pixel location, and $$\theta$$ is the counterclockwise angle to rotate. T means to transpose and is mostly there so that the row vector fits on the screen. You can ignore the 3rd row for now. Notice that because you are using sine and cosine functions, the new pixel location is unlikely to be an integer, so you will need to do some rounding.

However, if you are rotating around the center of the image (which is the more common use-case), you will need to first translate the "origin" of your image to the center, apply your rotation, then move your image back.

This alters the calculations to this:

$$\left[\begin{array}{c}x' \\y' \\1\end{array}\right]^T$$ $$=\left[\begin{array}{c}x \\y \\1\end{array}\right]^T$$ $$\begin{bmatrix}1 &0 &0\\0 &1 &0 \\-X/2 &-Y/2 &1\end{bmatrix}$$ $$\begin{bmatrix}\cos \theta &\sin \theta &0\\-\sin \theta & \cos \theta &0 \\0 &0 &1\end{bmatrix}$$ $$\begin{bmatrix}1 &0 &0\\0 &1 &0 \\X/2 &Y/2 &1\end{bmatrix}$$

$$=\left[\begin{array}{c}(x-X/2)\cos\theta + (y-Y/2)\sin\theta + X/2 \\-(x-X/2)\sin\theta+(y-Y/2)\cos\theta + Y/2 \\1\end{array}\right]^T$$

where capital X and Y are the size of your image in the x and y directions. You can read more about image transformations on the mathworks page here.

• There is an error in this answer: If you multiply your column vector (x y 1)^T from the right, then the translational part (X/2 and Y/2) must go in the rightmost column and not to the last row. The matrices you use are only correct if you multiply your vector (x y 1) as row vector from the left. The rotation matrix will rotate in your case into the other direction. In that sense, the information from the linked mathworks page is correct only for row vectors multiplied from the left. Jun 29, 2022 at 12:41