如何仅从 extcolor 获取 RGB 值

How to get only the RGB values from extcolor

我正在使用 extcolor 库来获取给定图像中的颜色。 return 是元组列表或元组列表的列表。这是列表中 5 个输入图像的输出。

color_list = [
     [((0, 113, 197), 25727)],
     [((4, 7, 7), 17739)],
     [((66, 133, 244), 6567), ((234, 67, 53), 4112), ((251, 188, 5), 2045), ((52, 168, 83), 1232), ((0, 255, 255), 32), ((255, 128, 0), 14), ((255, 255, 0), 9)],
     [((209, 54, 57), 39025), ((255, 255, 255), 10311), ((226, 130, 132), 204), ((0, 0, 0), 32)]
 ]

(a, b, c) 是我感兴趣的 RGB 值。如何只提取那些值?第一张图片只有一个 RGB 输出,而第三张图片有五个。

这是我的代码,每个图像中只有 returns 颜色值:

for logo in games:
    rand1, rand2, rand3 = (random.randint(0, 255),
                           random.randint(0, 255),
                           random.randint(0, 255))

    png = Image.open(logo).convert('RGBA')
    colors = extcolors.extract_from_path(logo)

    background = Image.new('RGBA', png.size, (rand1, rand2, rand3))

    alpha_composite = Image.alpha_composite(background, png)
    print(colors)

在所有示例中,我只看到 list of tuples,因此您可以使用相同的简单 for-loop 作为示例来提取数据。

color_list = [
     [((0, 113, 197), 25727)],
     [((4, 7, 7), 17739)],
     [((66, 133, 244), 6567), ((234, 67, 53), 4112), ((251, 188, 5), 2045), ((52, 168, 83), 1232), ((0, 255, 255), 32), ((255, 128, 0), 14), ((255, 255, 0), 9)],
     [((209, 54, 57), 39025), ((255, 255, 255), 10311), ((226, 130, 132), 204), ((0, 0, 0), 32)]
]

print('--- version 1 ---')

for example in color_list:
    result = []
    for item in example:
        result.append(item[0])
    print(result)

结果

[(0, 113, 197)]
[(4, 7, 7)]
[(66, 133, 244), (234, 67, 53), (251, 188, 5), (52, 168, 83), (0, 255, 255), (255, 128, 0), (255, 255, 0)]
[(209, 54, 57), (255, 255, 255), (226, 130, 132), (0, 0, 0)]

你也可以写成函数

print('--- version 2 ---')
    
def extract(data):
    result = []
    for item in data:
        result.append(item[0])
    return result

for example in color_list:
    result = extract(example)
    print(result)

或简称为列表理解

print('--- version 3 ---')
        
for example in color_list:
    result = [item[0] for item in example]
    print(result)

编辑:

单张图片示例

import extcolors

colors, pixels = extcolors.extract_from_path('lenna.png')

rgb_list = [x[0] for x in colors]

print(rgb_list)