尝试从图像中获取像素列表时获取错误'list'对象不可调用,

时间:2018-03-12 17:20:38

标签: python list pixels

我正在尝试从图像中提取像素值作为列表:

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

但是我收到了这个错误。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

您似乎已重新定义list。例如:

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

不要将list用作变量名。你按照show的方式编写代码,因此缺少一些分配给list并导致问题的代码:

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())
>>>

答案 1 :(得分:0)

我尝试了这个,它对我有用。

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)