【问题标题】:Image colors changed after saving with PIL使用 PIL 保存后图像颜色发生变化
【发布时间】:2022-08-21 04:07:45
【问题描述】:

我尝试创建由两列组成的非常简单的图像——一列绿色,另一列红色,但是当我运行如下所示的脚本时,我得到了其他颜色的图像。 知道为什么会这样吗?

from PIL import Image

list=[(0,255,00),(255,0,0),(0,255,00),(255,0,0),(0,255,00),(255,0,0)]
a=Image.new(\'RGB\',(2,3), \"white\")
a.putdata(list)
a.save(\'my_picture.jpg\')

我得到的图像: enter image description here

  • 顺便说一句,不要将变量命名为与预定义的 Python 变量相同的名称(例如,本例中的 list)。

标签: python image python-imaging-library rgb


【解决方案1】:

这是因为您将图像保存为 JPEG,默认情况下将启用各种选项来更改图像的颜色(因为 JPEG 是有损图像类型),尤其是Chroma Subsampling,这将改变“感知' 图像的颜色。由于您正在制作如此微小的图像,因此这种效果将非常引人注目,并导致您看到的颜色,默认情况下libjpeg 可能使用4:2:2 子采样(而不是4:4:4)。

你可以做几件事:

  1. 另存为 PNG

    如果您正在处理计算机图形图像(就像您现在正在做的那样)而不是照片级别的东西,请将您的图像保存为无损的 PNG。

    from PIL import Image
    
    pixels = [(0,255,00),(255,0,0),(0,255,00),(255,0,0),(0,255,00),(255,0,0)]
    a=Image.new('RGB',(2,3), "white")
    a.putdata(pixels)
    a.save('my_picture.png')
    

    你得到的图像看起来像这样

  2. 指定 JPEG subsampling=0subsampling="4:4:4"

    您可以使用subsampling=0 选择4:4:4 子采样,并获得最高级别的子采样以尽可能保留您想要的颜色。

    a.save("my_picture.jpg", quality=95, subsampling=0)
    

    您生成的 JPEG 看起来可能与您预期的一样:


    您可以看到更多关于如何处理image formats 的选项,以下是您可以指定给subsampling 的选项:

    subsampling
    
        If present, sets the subsampling for the encoder.
    
            keep: Only valid for JPEG files, will retain the original image setting.
    
            4:4:4, 4:2:2, 4:2:0: Specific sampling values
    
            0: equivalent to 4:4:4
    
            1: equivalent to 4:2:2
    
            2: equivalent to 4:2:0
    
        If absent, the setting will be determined by libjpeg or libjpeg-turbo.
    

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2019-12-04
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多