1

I am trying to extract pixel values from an image as a list:

from PIL import Image

im = Image.open('exp.jpg','r')
pix_val = list(im.getdata())
pix_val_flat = [x for sets in pix_val for x in sets]
print(pix_val_flat)

Error: 
  File "C:/Users/anupa/Desktop/All Files/LZW/Code/image.py", line 4, in <module>
    pix_val = list(im.getdata())

TypeError: 'list' object is not callable

But I am getting this error. Can anyone please help me?

ilanman
  • 818
  • 7
  • 20
  • 1
    See comments here: https://stackoverflow.com/questions/1109422/getting-list-of-pixel-values-from-pil . It could be because you are casting im.getdata() as a list() – ilanman Mar 12 '18 at 17:30
  • Thnaks.. Thanks woks for me. – Anupam Hayat Shawon Mar 12 '18 at 17:54
  • It's saying `list` (the variable) is not callable. That implies that the list type has been redefined. Do you have an assignment to list (e.g. `list = something`) earlier in the code? `print(type(list))` should return ``. – Mark Tolonen Mar 12 '18 at 19:37

2 Answers2

2

It looks like you've redefined list. For example:

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list()  # list is certainly callable...
[]
>>> type(list)
<class 'type'>
>>> list = [1,2,3]  # Now list is used as a variable and reassigned.
>>> type(list)
<class 'list'>
>>> list()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

Don't use list as a variable name. You're code as show works as is, so there is some code missing that is assigning to list and causing the problem:

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> im = Image.open('exp.jpg','r')
>>> pix_val = list(im.getdata())
>>>
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

I tried this and it works for me.

from PIL import Image
i = Image.open("Images/image2.jpg")

pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for x in range(width):
    for y in range(height):
        #cpixel = pixels[x, y]
        #all_pixels.append(cpixel)
        cpixel = pixels[x, y]
        bw_value = int(round(sum(cpixel) / float(len(cpixel))))
            # the above could probably be bw_value = sum(cpixel)/len(cpixel)
        all_pixels.append(bw_value)