gpt4 book ai didi

python - 将图像旋转 90° 时,如何阻止 PIL 交换高度/宽度?

转载 作者:太空狗 更新时间:2023-10-29 21:46:01 24 4
gpt4 key购买 nike

我正在使用 PIL旋转图像。这通常有效,除非我将图像恰好旋转 90° 或 270°,在这种情况下 x 和 y 测量值交换。也就是说,给定这张图片:

>>> img.size
(93, 64)

如果我将它旋转 89°,我会得到:

>>> img.rotate(89).size
(93, 64)

到 91° 我明白了:

>>> img.rotate(91).size
(93, 64)

但是如果我将它旋转 90° 或 270°,我会找到高度和宽度交换:

>>> img.rotate(90).size
(64, 93)
>>> img.rotate(270).size
(64, 93)

防止这种情况的正确方法是什么?

最佳答案

我希望有人想出一个更优雅的解决方案,但这似乎目前有效:

img = Image.open('myimage.pbm')

frames = []
for angle in range(0, 365, 5):
# rotate the image with expand=True, which makes the canvas
# large enough to contain the entire rotated image.
x = img.rotate(angle, expand=True)

# crop the rotated image to the size of the original image
x = x.crop(box=(x.size[0]/2 - img.size[0]/2,
x.size[1]/2 - img.size[1]/2,
x.size[0]/2 + img.size[0]/2,
x.size[1]/2 + img.size[1]/2))

# do stuff with the rotated image here.

对于 90° 和 270° 以外的角度,这会导致相同的行为如果你设置 expand=False 并且不理会 crop操作。

关于python - 将图像旋转 90° 时,如何阻止 PIL 交换高度/宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31303938/

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