重复在图像上创建文本的算法

时间:2015-07-09 19:37:21

标签: python arrays python-imaging-library

使用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

1 个答案:

答案 0 :(得分:1)

您可以将项目整理到一个集合中,该集合按类似的区号对它们进行分组。然后,对于每个区域,您可以使用增加的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