简体   繁体   English

Python的PIL裁剪问题:裁剪图像的颜色搞砸了

[英]Python's PIL crop problem: color of cropped image screwed

I have a probably very basic problem with PIL's crop function: The cropped image's colors are totally screwed. 我对PIL的裁剪功能有一个非常基本的问题:裁剪后的图像颜色完全拧紧。 Here's the code: 这是代码:

>>> 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()

The original image: 原始图片: 在此输入图像描述

and the output . 和输出

As you can see, the output's colors are totally messed up... 如你所见,输出的颜色完全搞砸了......

Thanks in advance for any help! 在此先感谢您的帮助!

-Hoff -Hoff

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

instead of 代替

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

just do 做就是了

area.save('cropped_football.jpg')

Since the call to save actually produced output, I have to assume that PIL is able to use either a filename or an open file interchangeably. 由于save实际生成输出的调用,我必须假设PIL能够交替使用文件名或打开文件。 The problem is in the file mode, which by default will try to convert based on text conventions - a '\\n' will be replaced by '\\r\\n' on Windows. 问题出在文件模式,默认情况下会尝试根据文本约定进行转换 - 在Windows上,'\\ n'将替换为'\\ r \\ n'。 You need to open the file in binary mode: 您需要以二进制模式打开文件:

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

PS I tested this and it works: PS我测试了它,它的工作原理:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM