【问题标题】:PIL unable to getcolors of a PNG Image (Image attached)PIL 无法获取 PNG 图像的颜色(附图像)
【发布时间】:2018-06-30 19:22:47
【问题描述】:

我正在处理一个非常基本的 PNG 图像,但是当我尝试加载它时,它会将所有像素都设为 (0)。图片链接:https://i.imgur.com/Oook1VX.png

from PIL import Image
myImage = Image.open("Oook1VX.png")
print(myImage.getpixel((0,0)))
print(myImage.getcolors())

输出:

0
[(2073600, 0)]

我希望它能够看到绿色?它适用于其他图像,但不适用于此图像。如果有人有任何想法,我将非常感激。

【问题讨论】:

    标签: python png python-imaging-library


    【解决方案1】:

    getcolors() 返回将颜色映射到数字的元组列表(用于压缩目的)。

    在您的示例中,该元组列表表示颜色 2073600 在图像中被编码为 0。因此,如果getpixel() 返回0,则表示2073600

    2073600 是十六进制的#1fa400,即图片中的绿色。

    您可能会受益于像这样自动解析颜色的包装器:

    import struct
    
    class PngImage:
        def __init__(self, image):
            self.image = image
            self._colors = {index: color for color, index in image.getcolors()}
    
        def getpixel(self, pos):
            color = self._colors[self.image.getpixel(pos)]
            return struct.unpack('3B', struct.pack('I', color))
    
    image = PngImage(Image.open("Oook1VX.png"))
    image.getpixel((0, 0)) # => (0x1f, 0x1f, 0x00)
    

    【讨论】:

    • 贝利的回答让我有点困惑。你说 2073600 是我图像中的绿色,但程序仍然输出 [(2073600, 0)] 即使颜色变为粉红色。 (图像有 2073600 像素)如果我把图像变小,它会输出: [(49887, (0, 127, 14))] 另外,当我完全运行你的代码时,它会输出: struct.error: unpack requires a bytes长度为 3 的对象请问我可以再帮忙吗?
    • @JimmyCarlos: getcolors 返回“...[an] unsorted list of (count, pixel) values”,所以在这方面贝利确实是错误的。但是:根据其他各种问题(您可能想阅读文档并在 Stack Overflow 上搜索),您使用的功能不能很好地工作,或者根本不能使用 indexed 彩色图像。如果您的图像被索引并且绿色是颜色#0,那么您的结果是绝对正确的。
    • 感谢您的评论。现在主帖中有一个图片链接,它是一个非常简单的 1920x1080 矩形,用 Paint.NET 制作,完全没有添加。
    • @JimmyCarlos:“没有添加”,是的,所以我注意到了。您可以添加“1920x1080,8 位调色板,非隔行扫描”,这正是我不得不猜测的。
    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 2011-06-07
    • 2010-12-30
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多