Python PIL裁剪问题:裁剪图像颜色错误

4 投票
3 回答
1655 浏览
提问于 2025-04-15 11:25

我遇到了一个可能很基础的问题,跟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 个回答

1

因为调用 save 实际上产生了输出,所以我可以推测 PIL(Python Imaging Library)可以用文件名或打开的文件来互换使用。问题出在文件模式上,默认情况下,它会根据文本的规则进行转换——在 Windows 系统上,'\n' 会被替换成 '\r\n'。所以你需要以二进制模式打开文件:

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

顺便说一下,我测试过这个方法,确实有效:

在这里输入图片描述

3

不要用

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

直接用

area.save('cropped_football.jpg')
4

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

撰写回答