Lamba_Jay
Lamba_Jay

Reputation: 11

ValueError: too many values to unpack (expected 3) using PIL

I have an image of pixel size (1761, 460) and I am trying to find RGB values with Python using PIL. The image has 56 distinct colors in it. I am running the following code but I get an error saying: ValueError: too many values to unpack (expected 3)

Does anybody know a better method of doing this finding RGB values of an image?

  import numpy as np
  import matplotlib.pyplot as plt
  import colorsys
  from PIL import Image

  img_file=Image.open("orange 4.png")
  img = img_file.load()
  [xs, ys] = img_file.size
   for x in range(0, xs):
           for y in range(0, ys):
            [r, g, b] = img[x, y]
              r /= 255.0
              g /= 255.0
              b /= 255.0

Upvotes: 1

Views: 4426

Answers (1)

Nicolas Abril
Nicolas Abril

Reputation: 161

Not all PNG files are born the same.

There are many ways of specifying pixel information in PNG, this document shows 8 basic types. Depending on which type your file is in, each pixel could have 1, 2, 3 or four values associated with each pixel.

I'm guessing the file you're trying to open is RGB with alpha channel. You could use send the pixel information to a list and iterate over it like:

pixel = img[x, y]
r, g, b = pixel[0], pixel[1], pixel[2]

You could try to identify what sort of PNG you're dealing with, or you could convert your image to RGB using:

img_file = img_file.convert('RGB')

Upvotes: 1

Related Questions