首页 > 解决方案 > 像素 RGB 值标识符 - 类型错误:参数必须是长度为 2 的序列

问题描述

我一直在使用 PIL 遇到问题,并试图让我的程序打印像素的 rgb 值。

代码

import PIL

try:
    import Image
except ImportError:
    from PIL import Image

###
    
filename = input ('Picture Filename - ')

image = PIL.Image.open(filename)

image.show()

width, height = image.size

image_rgb = image.convert('RGB')

w = 1
h = 1

a = 1
b = 2
while a < b:
    while (w <= width):
        rgb_pixel_value_1 = int(image_rgb.getpixel(w))
        rgb_pixel_value_2 = int(image_rgb.getpixel(h))
        print(rgb_pixel_value_1)
        print(rgb_pixel_value_2)
        w += 1
    if w == width and h < height:
        h += 1
    if h == height:
        a = 3

预期输出:程序应打印从 [1, 1] 到 [height, width] 的每个像素的值

实际输出:

Traceback (most recent call last):
  File "I:/Programming/Python/Useful Projects/Image Colour Space Checker/Revision 1.py", line 27, in <module>
    rgb_pixel_value_1 = int(image_rgb.getpixel(w))
  File "C:\Users\rdmor\AppData\Roaming\Python\Python38\site-packages\PIL\Image.py", line 1367, in getpixel
    return self.im.getpixel(xy)
TypeError: argument must be sequence of length 2

我尝试过的:我尝试过的很少,因为互联网上关于这个主题的内容太少了,任何相关的东西充其量只是稍微有用

可能还有其他错误,无论多么轻微,我还没有注意到

标签: pythonpython-imaging-librarypython-3.8

解决方案


从指定的 x 和 y 获取像素时,getpixel 期望传递一个长度为 2 的序列。在您的代码中,您有

rgb_pixel_value_1 = int(image_rgb.getpixel(w))

从您需要的指定位置获取 rgb 值

r, g, b = image_rgb.getpixel((w, h))

推荐阅读