2009-05-06 139 views
4

我有一个PIL的裁剪功能可能非常基本的问题:裁剪图像的颜色是完全拧紧的。下面的代码:Python的PIL裁剪问题:裁剪图像的颜色扭曲

>>> from PIL import Image 
>>> img = Image.open('football.jpg') 
>>> img 
<PIL.JpegImagePlugin.JpegImageFile instance at 0x00 
>>> img.format 
'JPEG' 
>>> img.mode 
'RGB' 
>>> box = (120,190,400,415) 
>>> area = img.crop(box) 
>>> area 
<PIL.Image._ImageCrop instance at 0x00D56328> 
>>> area.format 
>>> area.mode 
'RGB' 
>>> output = open('cropped_football.jpg', 'w') 
>>> area.save(output) 
>>> output.close() 

原始图像:enter image description here

and the output

正如你所看到的,输出的颜色是完全搞砸了......

在此先感谢您的帮助!

-Hoff

回答

4

output应该是一个文件名,而不是处理程序。

+1

那么,它可以是一个文件,但它需要在二进制模式被打开。尽管如此,最好让PIL在方便时处理。 – kindall 2011-07-26 16:29:31

3

代替

output = open('cropped_football.jpg', 'w') 
area.save(output) 
output.close() 

只是做

area.save('cropped_football.jpg') 
1

由于调用save实际产生的输出,我不得不假定PIL能够使用一个文件名或一个打开的文件互换。问题出在文件模式下,默认情况下会尝试根据文本惯例进行转换 - 在Windows上'\ r \ n'将替换'\ n'。您需要以二进制模式打开文件:

output = open('cropped_football.jpg', 'wb') 

P.S.我测试了这一点,它的工作原理:

enter image description here