【问题标题】:unsubscriptable object不可下标的对象
【发布时间】:2010-10-14 20:32:39
【问题描述】:

我正在使用 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]”行上得到“不可订阅的对象”。试过了:

if colors: 

变得真实并继续。

if len(colors):

给出'len() of unsized object'

  1. 我应该申请什么条件才不会获得此异常?
  2. 问题的原因是什么?

【问题讨论】:

    标签: python image image-processing colors python-imaging-library


    【解决方案1】:

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

    【讨论】:

    • dict(zip('rgb', colors if isinstance(colors, tuple) else [colors]*3))
    【解决方案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。

    【讨论】:

      【解决方案3】:

      来自 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.
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-22
        • 2020-02-17
        • 2021-11-10
        • 2019-05-16
        • 2016-07-20
        • 2011-08-20
        • 1970-01-01
        相关资源
        最近更新 更多