我正在使用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)
防止这种情况的正确方法是什么?
答案 0 :(得分:5)
我希望有人提出更优雅的解决方案,但这似乎现在有效:
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
操作