简体   繁体   中英

PIL unable to getcolors of a PNG Image (Image attached)

I am working on a very basic PNG image, but when I try to load it in, it gives all pixels as (0). Image link: https://i.imgur.com/Oook1VX.png

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

Output:

0
[(2073600, 0)]

I want it to be able to see the green? It worked for other images, but not this one. If anyone has any ideas I would be very appreciative.

getcolors() returns a list of tuples that map colors to numbers (for compression purposes).

In your example, that list of tuples says that the color 2073600 is encoded as 0 in the image. So if getpixel() returns 0 that means 2073600 .

2073600 is #1fa400 in hex, which is the green in your image.

You might benefit from a wrapper like this one that automatically resolves the colors:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM