Rotate Image in Python

PythonServer Side ProgrammingProgramming

Suppose we have one 2D matrix, that is representing one image. We have to rotate this image to 90 degrees clockwise. So if the image is like

157
963
213

Then the output will be

291
165
337

To solve this, we will follow these steps −

  • Consider temp_mat = [], col := length of matrix – 1
  • for col in range 0 to length of matrix
    • temp := []
    • for row in range length of matrix – 1 down to -1
      • add matrix[row, col] in temp
    • add temp into temp_mat
  • for i in range 0 to length of matrix
    • for j in range 0 to length of matrix
      • matrix[i, j] := temp_mat[i, j]

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def rotate(self, matrix):
      temp_matrix = []
      column = len(matrix)-1
      for column in range(len(matrix)):
         temp = []
         for row in range(len(matrix)-1,-1,-1):
            temp.append(matrix[row][column])
         temp_matrix.append(temp)
      for i in range(len(matrix)):
         for j in range(len(matrix)):
            matrix[i][j] = temp_matrix[i][j]
      return matrix
ob1 = Solution()
print(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]]))

Input

[[1,5,7],[9,6,3],[2,1,3]]

Output

[[2,9,1],[1,6,5],[3,3,7]]
raja
Published on 31-Jan-2020 05:59:08
Advertisements