Python 如何从extcolor仅获取RGB值
我正在使用Python 如何从extcolor仅获取RGB值,python,regex,python-imaging-library,extcolors,Python,Regex,Python Imaging Library,Extcolors,我正在使用extcolor库获取给定图像中的颜色。返回的是元组列表或元组列表。这是列表中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), ((2
extcolor
库获取给定图像中的颜色。返回的是元组列表或元组列表。这是列表中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输出,而第三个图像有五个RGB输出
这是我的代码,它只返回每个图像中的颜色值:
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)
在所有示例中,我只看到元组列表,因此您可以使用相同的简单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)
示例输入图像的预期结果是什么?你试过哪个正则表达式?我还没试过正则表达式。还有,你所说的预期结果是什么意思?我只想从输入中取出元组..我没有看到元组列表-在所有示例中,我都看到了
元组列表
。因此,在所有示例中,您都可以使用相同的列表理解
或正常的for
-循环来获得期望值。您在列表的括号中犯了一个错误。它是这样的:example=[[(…
我从你的问题中复制了数据-所以最终你会出错:)对不起。我修正了它。你现在可以看一下吗?我如何将你的逻辑应用到这个列表中?我测试它-在当前版本中,我只需删除[0]
,它的工作原理是一样的。当我索引0时,我得到[((0,113,197),25727)]