代码之家  ›  专栏  ›  技术社区  ›  Hoff

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

  •  4
  • Hoff  · 技术社区  · 17 年前

    我对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 .

    正如你所看到的,输出的颜色完全乱了。。。

    -霍夫

    3 回复  |  直到 15 年前
        1
  •  4
  •   SilentGhost    17 年前

    output

        2
  •  3
  •   fastmultiplication    17 年前

    而不是

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

    照办

    area.save('cropped_football.jpg')
    
        3
  •  1
  •   Mark Ransom    15 年前

    自从打电话给 save 实际生成的输出,我必须假设PIL能够互换地使用文件名或打开的文件。问题出在文件模式下,默认情况下,该模式将尝试根据文本约定进行转换-在Windows上,'\r\n'将替换为'\r\n'。您需要以二进制模式打开文件:

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

    P.S.我对此进行了测试,结果表明:

    enter image description here

    推荐文章