在Python中根据整数列表生成多色线段

2024-04-19 23:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个线段与多种颜色根据输入的颜色代码给出的整数列表。例如,假设有一个包含颜色代码的整数n和元组的列表

n= [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]

codes=([1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Blue'])

然后,我想要一个线段,它是根据给定整数序列中的颜色代码由多种颜色组成的。请找到这张图片以供参考

image

给定的图像具有大约100个整数的输入序列长度和相应的色码。这样的东西怎么能建造出来呢?你知道吗


Tags: 图像列表颜色图片序列整数greenblue
1条回答
网友
1楼 · 发布于 2024-04-19 23:24:01

python中解决这类问题的一个好方法是PIL库:

代码:

from PIL import Image, ImageDraw

def colored_bar(data, colors, height=10, width=5):
    # Create a blank image
    im = Image.new('RGBA', (width * len(data), height), (0, 0, 0, 0))

    # Create a draw object
    draw = ImageDraw.Draw(im)

    for i, val in enumerate(data):
        draw.rectangle((i * width, 0, (i+1) * width, height),
                       fill=colors[val])
    return im

测试代码:

n = [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]
codes = dict(([1, 'red'], [2, 'yellow'], [3, 'green'], [4, 'blue']))

image = colored_bar(n, codes)
image.show()

结果:

enter image description here

相关问题 更多 >