lar*_*sks 7 python python-imaging-library
我正在使用PIL来旋转图像.这通常起作用,除非我将图像精确旋转90°或270°,在这种情况下x和y测量值交换.也就是说,鉴于此图像:
>>> img.size
(93, 64)
Run Code Online (Sandbox Code Playgroud)
如果我将它旋转89°,我得到这个:
>>> img.rotate(89).size
(93, 64)
Run Code Online (Sandbox Code Playgroud)
到了91°,我得到了这个:
>>> img.rotate(91).size
(93, 64)
Run Code Online (Sandbox Code Playgroud)
但如果我将其旋转90°或270°,我会发现交换的高度和宽度:
>>> img.rotate(90).size
(64, 93)
>>> img.rotate(270).size
(64, 93)
Run Code Online (Sandbox Code Playgroud)
什么是防止这种情况的正确方法?
我希望有人提出一个更优雅的解决方案,但这似乎现在有效:
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.
Run Code Online (Sandbox Code Playgroud)
对于90°和270°以外的角度,如果设置expand=False并且不打扰crop
操作,则会产生与您获得的相同的行为.