在 Python 中旋转图像

pythonserver side programmingprogramming更新于 2025/10/25 17:48:17

假设我们有一个 2D 矩阵,它代表一个图像。我们必须将此图像顺时针旋转 90 度。因此,如果图像如下

157
963
213

则输出将是

291
165
337

为了解决这个问题,我们将遵循以下步骤 −

  • 考虑 temp_mat = [], col := 矩阵长度 – 1
  • 对于 col,范围从 0 到矩阵长度
    • temp := []
    • 对于 row,范围从矩阵长度 – 1 到 -1
      • 将 matrix[row, col] 添加到 temp 中
    • 将 temp 添加到 temp_mat 中
  • 对于 i,范围从 0 到矩阵长度
    • 对于 j,范围从 0 到矩阵长度
      • matrix[i, j] := temp_mat[i, j]

示例 (Python)

让我们看下面的实现,以便更好地理解 −

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

输入

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

输出

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

相关文章


有用资源