根据编码特定颜色的整数列表在 Python 中制作多个彩色线段
Making multiple coloured line segment in Python according to a list of integers coding for a specific color
我想根据作为整数列表给出的颜色代码的输入来制作具有多种颜色的线段。例如,假设有一个整数列表 n 和包含颜色代码
的元组
n= [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]
codes=([1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Blue'])
然后,我想要一个线段,根据给定的整数序列中的颜色代码,由多种颜色组成。请找到此图片以供参考
给定的图像具有大约 100 个整数的输入序列长度和相应的颜色代码。这样的东西怎么构造?
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()
结果:
我想根据作为整数列表给出的颜色代码的输入来制作具有多种颜色的线段。例如,假设有一个整数列表 n 和包含颜色代码
的元组n= [1, 2, 1, 3, 4, 2, 3, 1, 1, 2, 3]
codes=([1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Blue'])
然后,我想要一个线段,根据给定的整数序列中的颜色代码,由多种颜色组成。请找到此图片以供参考
给定的图像具有大约 100 个整数的输入序列长度和相应的颜色代码。这样的东西怎么构造?
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()
结果: