Search code examples
pythonimage-processingpython-imaging-librarypng

Error when trying to extract RGB values from PNG Image [Python PIL]


I'm trying to create a simple image processing program in Python and the program works fine with .jpg files. Unfortunately, I can't ever seem to make it work for .png files and I really can't understand why.

Here's my code for getting the image and extracting the individual RGB values of each pixel:

image1 = Image.open('fake4.png')
            
pixels1 = image1.load()
  
for i in range(image1.size[0]): #column
    for j in range(image1.size[1]): #row
        r, g, b = image1.getpixel((i, j))
        #perform some checks on individual RGB values

When I run the code, it works fine for jpeg images, but with .png images I always get one of two errors at the line r, g, b = image1.getpixel((i, j)).

These errors are either:

builtins.ValueError: too many values to unpack (expected 3)

or

builtins.TypeError: cannot unpack non-iterable int object

Python Image Library is something I'm new to and so is image processing in general.

Any ideas why is issue is caused and how to resolve it?


Solution

  • Thanks to Nicolas Gervais for helping me figure out that the image I was attempting to process was actually a greyscale image. Because of that the getpixel() function would only return one value.

    As such, I solved the issue by converting the image to RGBA format and that did the trick:

    Here's my code for the workaround:

    initialImage = Image.open('fake4.png')
    image1 = Image.new("RGBA", initialImage.size)
    image1.paste(initialImage) 
    

    Not sure of this is the most efficient way to do it, but it does the trick.