Python - Cannot unpack non-iterable int object

本秂侑毒 提交于 2021-01-29 01:42:25

问题


I'm trying to get an Image's pixel RGB with the PIL Image Library.

With this code, I ran into the error:

for i in range(width):
    for j in range(height):

        r,g,b=(image.getpixel((i,j))) #THIS LINE IS REFERENCED IN ERROR MESSAGE
        print("leds[",j,"] = CRGB(",r, "," ,g, ",", b, ");") #print pixel colorchange to console

del image

Why do I get this error? To me, this seems really strange. I input 2 images and it works just fine. However when I have white pixels at a certain position in the image, I get the error:

line 18, in <module> 
r,g,b=(image.getpixel((i,j))) #Get pixel at coordinate
TypeError: cannot unpack non-iterable int object

The Images that worked: ColorCycle, HelloWorld

Image that didnt work: HelloWorld2 This Image has a few white pixels on the right.

Full code here.


回答1:


The problem appears to be that the image you are looking at is not an RGB image. If you look at image.getbands() or image.mode, you will see that the image is in mode P, the palette mode.

In this mode, instead of storing values color values directly for each pixel, each pixel stores one number, which is an index into the image's palette, which is accessible via getpalette. The palette itself could be in a variety of "modes," but for this particular image, it is an RGB palette of the form [r0, g0, b0, r1, g1, b1, ...].

So one way to get the actual pixel values of the image would be to check the mode and manually get the r, g, b, values out.

palette = image.getpalette()
for i in range(width):
    for j in range(height):
        index = image.getpixel((i, j))  # index in the palette
        base = 3 * index  # because each palette color has 3 components
        r, g, b = palette[base:base+3]

However, there is a shortcut in this case; you can convert between modes using the aptly-named convert function.

rgb_image = image.convert('RGB')

Note, however, that using convert blindly may have unexpected consequences (possibly without causing any Python errors) if you run into images that use other modes.



来源:https://stackoverflow.com/questions/59723475/python-cannot-unpack-non-iterable-int-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!