代码之家  ›  专栏  ›  技术社区  ›  zalew

不可订阅对象

  •  1
  • zalew  · 技术社区  · 17 年前

    我在用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
    

    问题是,在一些(非常少,特别是我不知道为什么是那些简单的JPEG)上,我在“colors[0]”一行得到了“unsubscribable object”。尝试:

    if colors: 
    

    变得真实并继续。

    if len(colors):
    

    给出“未调整大小的对象的len()”

    1. 我应该应用什么条件才能不获得此异常?
    3 回复  |  直到 17 年前
        1
  •  4
  •   Ignacio Vazquez-Abrams    17 年前

    从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.
    

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

        2
  •  2
  •   mipadi    17 年前

    如另一份答复所述, 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
    

    第二种方式可能更像蟒蛇。

        3
  •  2
  •   zalew    17 年前

    好的,情况是,当B&W图像没有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}