【问题标题】:Python's PIL crop problem: color of cropped image screwedPython PIL裁剪问题:裁剪图像的颜色拧紧
【发布时间】:2010-10-24 05:47:54
【问题描述】:

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

原图:

and the output.

如您所见,输出的颜色完全混乱...

提前感谢您的帮助!

-霍夫

【问题讨论】:

    标签: python image-processing colors python-imaging-library crop


    【解决方案1】:

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

    【讨论】:

    • 嗯,可以是文件,但是需要以二进制方式打开。不过,最好让 PIL 在方便的时候处理它。
    【解决方案2】:

    而不是

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

    只是做

    area.save('cropped_football.jpg')
    

    【讨论】:

      【解决方案3】:

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

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

      附:我对此进行了测试,并且可以正常工作:

      【讨论】:

        猜你喜欢
        • 2011-04-19
        • 2017-05-22
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        • 2013-03-05
        • 2012-12-22
        • 2011-09-21
        • 2015-09-30
        相关资源
        最近更新 更多