我正在使用PIL。
im = im.rotate(angle=-90, expand = True)
当我这样做时,它会为我的图像添加灰色边框。
为什么?
这是完整的代码。请注意,如果我不旋转,则不会添加边框
def fixRotation(f, quality=96, image_type="JPEG"):
#http://sylvana.net/jpegcrop/exif_orientation.html
d =getEXIF(f)
if d:
orientation = int(d['Orientation'])
im = Image.open(StringIO(f))
if orientation == 6:
im = im.rotate(angle=-90, expand = True)
elif orientation == 3:
im = im.rotate(angle=-180, expand=True)
elif orientation == 8:
im = im.rotate(angle=-270, expand=True)
else:
#It doesn't add a border here.
im = im.rotate(0, expand=True)
res = StringIO()
im.save(res, image_type, quality=quality)
res.seek(0)
return res
else:
return StringIO(f)
答案 0 :(得分:1)
我做了一些实验,确实改变了图像尺寸,但我没有强调确切的行为。对我来说,看起来像是PIL中的一个错误...你应该报告它。
如果您只需要k * 90度然后进行旋转,您也可以使用numpy ......
img = Image.fromarray(numpy.rot90(numpy.array(img), n))
n
是旋转90度的次数。
答案 1 :(得分:0)
请注意以下内容(CPython 2.6,PIL 1.1.7):
import Image
i= Image.open("someimage.jpg")
ir0= i.rotate(-90)
ir1= i.rotate(-90, expand=1)
for img in i, ir0, ir1:
print(img.size)
# output follows
(720, 400)
(400, 720)
(401, 721)
angle
是90的倍数,则不需要expand
。expand
似乎激活了一个错误所以,如果您关心的是90°-180°-270°旋转,只需删除expand=1
参数;更好的是,使用transpose
方法(参见PIL tutorial中的几何变换)
答案 2 :(得分:0)
旋转时,算法(基本上)用“下一个”像素值平均每个像素。对于图像“内部”的所有像素,定义下一个像素。对于图像边缘的所有像素,该像素未定义。
因此,灰色是已知周边像素与未定义外部像素之间的平均值。