Python的PIL裁剪问题:裁剪后图像颜色失真

4

我在使用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()

原始图片:在此输入图片描述 输出结果如上图所示,颜色完全混乱...
感谢您的帮助!
-Hoff
3个回答

4

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


1
好的,它可以是一个文件,但需要以二进制模式打开。不过,最好在方便的时候让PIL处理它。 - kindall

3

替代

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

只需要做

area.save('cropped_football.jpg')

1

由于对save的调用实际上产生了输出,我必须假设PIL能够交替使用文件名或打开的文件。问题在于文件模式,默认情况下将尝试根据文本约定进行转换 - 在Windows上,'\n'将被替换为'\r\n'。您需要以二进制模式打开文件:

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

附言:我测试过这个代码,它可以正常工作:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接