質問

私が使っているときに呼び

    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

問題は、いずれかの非常に少ない柔らかさがなぜそう簡単に通報)を取得します'unsubscriptableオブジェクトの"線"色[0]".た:

if colors: 

がtrueでいただければと思います。

if len(colors):

を'len()の。オブジェクト'

  1. どういう状態にこのような状況での出願はこの例外?
  2. その原因の問題なのでしょうか。
役に立ちましたか?

解決

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.

だから、あなたのイメージの一部が多層であり、いくつかは、単層であることを思わます。

他のヒント

別の答えで述べたように、

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

第二の方法は、おそらくよりPython的です。

玉場合は、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}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top