gpt4 book ai didi

python - 将图像旋转 90 度

转载 作者:行者123 更新时间:2023-12-04 04:14:32 26 4
gpt4 key购买 nike

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

我相信我的代码似乎不起作用,因为我创建了新图像并且反转了原始图片中的宽度、长度和坐标。如何修复我的代码以正确旋转图像?

最佳答案

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

  • yx
  • 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

关于python - 将图像旋转 90 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com