如何使用python选择多个文本坐标,以使其不与同一背景图像中的多个图像坐标重叠?

时间:2019-01-06 04:20:28

标签: python python-3.x image image-processing python-imaging-library

我正在尝试使用python PIL库在背景图像上复制文本和图像。我想要实现这一点,以使新图像和文本不会彼此重叠或接触到边框,它们必须分别放置在单个背景图像上。图像大小和文本大小无关紧要,但可以容纳在背景图像中,至少必须有一个图像和文本。我为实现这一目的而编写的脚本如下

img = Image.open('imagefolder').resize((600,200))
b,l = img.size
width=20
height=20   
while height<l-10:
    hmax=0
    width=10
    select = random.choice([True,False])
    ran_height = random.choice(range(5,55))
    if select:
        while width<b:
            image_folder=random.choice(image_folders)            
            imagetemp=img.open(image_folder)
            size_w,size_h=imagetemp.size
            if size_h>hmax:
                hmax=size_h
            select_word = random.choice([True,False])
            d.text([10,30], "hello", helvetica)
            d.text([90,60], "python", helvetica)
            if select_word:
                if (width+size_w)<b-10 and (height+size_h)<l-10 :
                    (x, y) = (width, height)
                    image.paste(imagetemp,(x, y))                                               
                    width = width+size_w+10
                else:
                    height = height+hmax+10
                    break
            else:
                width =width+size_w+10
        height = height+hmax+10
    else:
        height = height+ran_height+10

在此代码中,

  

d.text([10,30],“你好”,helvetica)   d.text([90,60],“ python”,helvetica)

分别在坐标(10,30)和(90,60)中打印文本'hello'和'python'。和

  

image.paste(imagetemp,(x,y))

以(x,y)的坐标打印图像 我想为这样的文本传递一个坐标值,这样它就不会落在图像坐标下,或者文本不会与图像重叠。例如 image 如果我传递图像坐标值

  

d.text([x,y],“ hello”,helvetica)

文本将被打印在图像内,这不是我想要的,我想在图像外打印。让我知道你是否有任何问题。我在网上搜索时甚至没有找到执行此操作的单个示例,有许多示例使用PIL在图像内部而不是图像外部复制文本。任何建议都会有所帮助。

**通过查找文本大小将其修复

  

draw_txt.textsize(random_text,font = font)**

1 个答案:

答案 0 :(得分:0)

**通过查找文本大小将其修复

  

draw_txt.textsize(random_text,font = font)**