一种在图像上重复生成文本的算法

2024-04-23 16:04:18 发布

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

使用Python和PIL,我打算在现有图像上绘制文本。你知道吗

我有一个图像,上面有12个部分,我有一个数组,如下所示:

array = [
    [1,'ABC'],
    [2,'DEF'],
    [3,'XYZ'],
    [4,'aa1'],
    [1,'pqr'],
    [7,'etc'],
    [3,'klm'],
    [9,'bb'],
    [2,'aa'],
    [10,'xyz'],
    [11,'abc'],
    [1,'def'],
]

现在,根据a[0] for a in array中的数字,我将a[1]的文本放在图像的1-12部分。我试过这个:

for a in arr_vals:
    if a[0] == 1:
        draw.text((337, 140), a[1], (231, 76, 60), font=font)
    elif a[0] == 2:
        draw.text((149, 62), a[1], (231, 76, 60), font=font)
    elif a[0] == 3:
        draw.text((337, 156), a[1], (231, 76, 60), font=font)

现在很明显,出现的问题是,比如在上面的例子中,array[0]array[4]在第一个索引中有相同的值。这将导致图像中的文本被覆盖。在这种情况下如何防止覆盖?在图像上递归放置文本的理想算法是什么?你知道吗

编辑:

我想要的是:根据数组的不同,红色文本应该出现在12个部分中的任何一个。你知道吗

enter image description here

生成的当前图像:

如您所见,由于代码中的位置相同,生成的图像与文本重叠。 enter image description here


Tags: textin图像文本forpildef绘制
1条回答
网友
1楼 · 发布于 2024-04-23 16:04:18

您可以将项目组织到一个集合中,并按相似的区号对其进行分组。然后,对于每个区域,可以使用递增的y坐标渲染第一行以外的每一行文本,以便后面的行显示在前面的行的下方,而不是直接显示在它们的上方。示例:

array = [
    [1,'ABC'],
    [2,'DEF'],
    [3,'XYZ'],
    [4,'aa1'],
    [1,'pqr'],
    [7,'etc'],
    [3,'klm'],
    [9,'bb'],
    [2,'aa'],
    [10,'xyz'],
    [11,'abc'],
    [1,'def'],
]

d = {}
for item in array:
    d.setdefault(item[0], []).append(item[1])
print d

#d now contains something that looks like:
#{1: ['ABC', 'pqr', 'def'], 2: ['DEF', 'aa'], 3:...}

#height of a single line of text, in pixels.
#I don't know what this should actually be. Depends on your font size, I guess.
line_height = 20

color = (231, 76, 60)
for area in d.iterkeys():
    #somehow get the base coordinates for this particular area.
    #you originally used a lot of if-elifs, but a dict could work too.
    coords = ???
    y_offset = 0
    for line in d[area]:
        draw.text(coords[0], coords[1]+y_offset, line, color, font=font)
        y_offset += line_height

相关问题 更多 >