v9.1.1
Menu

Image Rotation

easyFREEImage manipulationLinear AlgebraCV - DSA

Implement an image rotation algorithm to rotate an n×nn \times n 2D matrix representing an image by 90 degrees in the clockwise direction. The image must be rotated in-place, meaning the input 2D matrix is modified directly without allocating additional memory. Return the rotated matrix.

The concept of image rotation is fundamental in image manipulation and computer vision, as it allows for the transformation of images to achieve desired orientations. This process involves applying a transformation matrix to the original image, which can be represented mathematically using linear algebra and matrix operations.

For a 2×22 \times 2 image, a clockwise rotation looks like this:

(abcd)→(cadb)\begin{pmatrix} a & b \\ c & d \end{pmatrix} \rightarrow \begin{pmatrix} c & a \\ d & b \end{pmatrix}

This technique is widely used in image processing applications.

Example

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]
Reasoning
  • matrix is a 3×33 \times 3 grid of pixel values: the top row is 1,2,31, 2, 3, the middle row 4,5,64, 5, 6, the bottom row 7,8,97, 8, 9.
  • A clockwise quarter turn tips the left edge up into the top edge, so the left column read from bottom to top, 7,4,17, 4, 1, becomes the new top row.
  • The same happens to the middle column (8,5,28, 5, 2 becomes row 2) and the right column (9,6,39, 6, 3 becomes row 3), giving [[7,4,1],[8,5,2],[9,6,3]].
  • In general, the value at row rr, column cc (counting from 1) lands at row cc, column n+1−rn + 1 - r. Check with 77: it starts at row 3, column 1 and lands at row 1, column 3+1−3=13 + 1 - 3 = 1.
  • Notice the four corners trade places in a cycle (11 goes top-right, 33 bottom-right, 99 bottom-left, 77 top-left) while the centre 55 stays put. The result keeps its n×nn \times n shape.

Constraints

1 <= n, m <= 100; Elements of matrix and vector can be integers or floats.

More from CV - DSA

solution.py

Test results

Sign in to run your code against the test cases.