旋转图像90度

3
def rotate_picture_90_left(img: Image) -> Image:
    """Return a NEW picture that is the given Image img rotated 90 degrees
    to the left.

    Hints:
    - create a new blank image that has reverse width and height
    - reverse the coordinates of each pixel in the original picture, img,
        and put it into the new picture
    """
    img_width, img_height = img.size
    pixels = img.load()  # create the pixel map
    rotated_img = Image.new('RGB', (img_height, img_width))
    pixelz = rotated_img.load()
    for i in range(img_width):
        for j in range(img_height):
            pixelz[i, j] = pixels[i, j]
    return rotated_img

我认为我的代码似乎不能正常工作是因为我创建了一个新的图像,以及对原始图像中的宽度、长度进行反转,还翻转了坐标。我该如何修复我的代码以正确旋转图像?

1个回答

1

将坐标转换时需要考虑以下逻辑:

  • y 转换为 x
  • x 转换为从结尾到开头的 y

以下是代码:

from PIL import Image

def rotate_picture_90_left(img: Image) -> Image:
    w, h = img.size
    pixels = img.load()
    img_new = Image.new('RGB', (h, w))
    pixels_new = img_new.load()
    for y in range(h):
        for x in range(w):
            pixels_new[y, w-x-1] = pixels[x, y]
    return img_new

例子:

enter image description hereenter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接