3

I was trying to run a python script (python 2.6) which contains the code as below

import Image

def is_grey_scale(img_path="lena.jpg"):
    im = Image.open(img_path)
    w,h = im.size
    for i in range(w):
        for j in range(h):
            r,g,b,_ = im.getpixel((i,j))
            if r != g != b:
                return False

    return True

It is reporting error as defined below.

r,g,b, _ = im.getpixel((i, j))
TypeError: 'int' object is not iterable

Can you please let me know what is the error here.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
kadina
  • 5,042
  • 4
  • 42
  • 83

2 Answers2

4

The situation is as follows

You are trying to unpack result returned from im.getpixel((i, j)) into 4 variables r, g, b, _.

For this to work, the im.getpixel has to return a list, a tuple or another iterable, which will provide just 4 values for the variables. Providing more or less makes a problem.

But in your case, the function im.getpixel((i, j)) is returning an int, which is not by any means an iterable, so it complains.

Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98
  • 2
    Or you can try `a, b, c = 1` and you'll get a `TypeError`, like the answer suggests. – huu May 14 '14 at 21:48
  • @msvalkon Your case is valid in your sample, but there you definitely return an iterable. But as Huu Nguyen notes, assign `a, b = 1` and you get `TypeError` – Jan Vlcinsky May 14 '14 at 21:51
  • 1
    For completeness, if you want to access `r, b, g` values of a pixel, you have to convert the image to an RGB or RGBA image. See this [answer](http://stackoverflow.com/a/11064935/2297365) for more details. – huu May 14 '14 at 21:52
1

The definition of the method is.

    def getpixel(self, xy):
        """
        Returns the pixel value at a given position.

        :param xy: The coordinate, given as (x, y).
        :returns: The pixel value.  If the image is a multi-layer image,
            this method returns a tuple.

Is your image a "multi-layer image" ? I assume its the same image used all over image processing Courses. Lena on wikipedia

LGama
  • 561
  • 4
  • 10