首页 > 解决方案 > 在不使用包和使用变换矩阵的情况下在 Python 中旋转彩色图像

问题描述

我正在尝试创建一种将 Python 中的彩色图像旋转 0、90、180 或 270 度的方法。到目前为止,这是我的代码。就目前而言,输出是空白图像。我也试图让代码尽可能高效。不知道我做错了什么。Image 是一个 3D 数组,而 rotate_angle 是一个 int。我尝试的想法是从原始图像中获取像素的所有 (x,y) 坐标,并将它们与变换矩阵 (x_transformed, y_transformed) 相乘。然后,新图像上 (x_transformed, y_transformed) 处的颜色将只是旧图像上 (x,y) 处的颜色。

def rotate_image(image, rotate_angle):
    output_image = image
    # Convert degrees to radian
    angle = math.radians(rotate_angle)
    # For all values of height
    for i in range(image.shape[0]):
        # And all values of width
        for j in range(image.shape[1]):
            # Take the x and y coordinates of the existing points
            y = image.shape[0]-1
            x = image.shape[1]-1
            # Keep in mind rotation matrix is [(cos, sin), (-sin, cos)] [(x,y)]
            y_n = int(-x * math.sin(angle) + y * math.cos(angle))
            x_n = int(x * math.cos(angle) + y * math.sin(angle))
            # Rotating to where we are and then copying data from where we were
            output_image[y_n, x_n, :] = image[i, j, :]
    return output_image

当然,如果有更高效的方法,我也有兴趣知道它是什么。我知道那里有可以做我正在做的事情的包,但我希望自己和使用我拥有的工具来制作方法。

标签: pythonarraysmatriximage-rotation

解决方案


推荐阅读