ali
ali

Reputation: 11

error: too many values to unpack

I'm trying to run this python code to read an image and convert it into a matrix of data, but I encounter the error above, and I hope you can help me in figuring out what is going one

from PIL import Image
from numpy import array
import numpy as np



img = Image.open('felix.png')
arr = array(img)

im = Image.open("felix.png")
col,row =  im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
    for j in range(col):
        r,g,b =  pixels[i,j]
        data[i*col + j,:] = r,g,b,i,j




print (data)

the error, Value error: too many values to unpack is for this line: r,g,b = pixels[i,j]

Thanks a a lot

Upvotes: 1

Views: 3772

Answers (2)

tsveti_iko
tsveti_iko

Reputation: 7972

If you have multiple images with different bands (RGB/RGBA) and you don't want to filter them then just do this:

band = pixels[i,j]
r = band[0]
g = band[1]
b = band[2]

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308121

This error means that each pixel contains more than the 3 values you've provided variables for. It's reasonable to assume that these are actually RGBA pixels.

r,g,b,a = pixels[i,j]

This won't be the case for every PNG file you open, so you need to be able to deal with this situation dynamically.

Upvotes: 5

Related Questions