1

我正在使用 PIL

    im = Image.open(teh_file)
    if im:
        colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color
        red = colors[0] # and so on, some operations on color data

问题是,在一些(很少,特别是不知道为什么那些确切的,简单的 jpegs)上,我在“colors [0]”行上得到“不可订阅的对象”。试过:

if colors: 

变得真实并继续。

if len(colors):

给出 'len() of unsized object'

  1. 我应该申请什么条件才能获得此例外?
  2. 问题的原因是什么?
4

3 回答 3

4

来自 PIL 文档:

getpixel

im.getpixel(xy) => value or tuple

Returns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple.

所以看起来你的一些图像是多层的,有些是单层的。

于 2009-03-22T18:00:57.633 回答
2

如另一个答案中所述,getpixel返回单个值或元组。您可以通过以下方式检查类型并执行适当的操作:

if isinstance(colors, tuple):
    color = colors[0]
else:
    color = colors
# Do other stuff

或者:

try:
    color = colors[0]
except: # Whatever the exception is - IndexError or whatever
    color = colors
# Do other stuff

第二种方式可能更 Pythonic。

于 2009-03-22T18:06:25.933 回答
2

好的情况是,当黑白图像没有 RGB 波段(L 波段)时,它返回一个具有像素颜色单一值的整数,而不是 rgb 值的列表。解决方案是检查波段

im.getbands()

或者更简单的我的需要是:

        if isinstance(colors, tuple):
            values = {'r':colors[0], 'g':colors[1], 'b':colors[2]}
        else:
            values = {'r':colors, 'g':colors, 'b':colors}
于 2009-03-22T19:43:35.437 回答