Python - 无法解压不可迭代的 int 对象
Python - Cannot unpack non-iterable int object
我正在尝试使用 PIL
Image
库获取图像的像素 RGB。
使用这段代码,我运行进入错误:
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
为什么会出现此错误?
对我来说,这似乎真的很 st运行ge。我输入了 2 张图像,效果很好。但是,当我在图像中的某个位置有白色像素时,出现错误:
line 18, in <module>
r,g,b=(image.getpixel((i,j))) #Get pixel at coordinate
TypeError: cannot unpack non-iterable int object
有效的图像:
ColorCycle,
HelloWorld
无效的图像:
HelloWorld2
此图片右侧有几个白色像素。
完整代码here.
问题似乎是您正在查看的图像不是 RGB 图像。如果您查看 image.getbands()
或 image.mode
,您将看到图像处于模式 P
、the palette mode.
在此模式下,不是直接为每个像素存储颜色值,而是每个像素存储一个数字,这是图像调色板的索引,可通过 getpalette
访问。调色板本身可以是各种 "modes," 但对于这个特定图像,它是 [r0, g0, b0, r1, g1, b1, ...]
.
形式的 RGB 调色板
因此,获取图像实际像素值的一种方法是检查模式并手动获取 r
、g
、b
值。
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]
然而,在这种情况下有一个捷径;您可以使用恰当命名的 convert
function.
在模式之间进行转换
rgb_image = image.convert('RGB')
但是请注意,如果您 运行 进入使用其他模式的图像,盲目使用 convert
可能会产生意想不到的后果(可能不会导致任何 Python 错误)。
我正在尝试使用 PIL
Image
库获取图像的像素 RGB。
使用这段代码,我运行进入错误:
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
为什么会出现此错误? 对我来说,这似乎真的很 st运行ge。我输入了 2 张图像,效果很好。但是,当我在图像中的某个位置有白色像素时,出现错误:
line 18, in <module>
r,g,b=(image.getpixel((i,j))) #Get pixel at coordinate
TypeError: cannot unpack non-iterable int object
有效的图像: ColorCycle, HelloWorld
无效的图像: HelloWorld2 此图片右侧有几个白色像素。
完整代码here.
问题似乎是您正在查看的图像不是 RGB 图像。如果您查看 image.getbands()
或 image.mode
,您将看到图像处于模式 P
、the palette mode.
在此模式下,不是直接为每个像素存储颜色值,而是每个像素存储一个数字,这是图像调色板的索引,可通过 getpalette
访问。调色板本身可以是各种 "modes," 但对于这个特定图像,它是 [r0, g0, b0, r1, g1, b1, ...]
.
因此,获取图像实际像素值的一种方法是检查模式并手动获取 r
、g
、b
值。
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]
然而,在这种情况下有一个捷径;您可以使用恰当命名的 convert
function.
rgb_image = image.convert('RGB')
但是请注意,如果您 运行 进入使用其他模式的图像,盲目使用 convert
可能会产生意想不到的后果(可能不会导致任何 Python 错误)。