我正在尝试使用Python Imaging Library(PIL)将3张图像放入具有随机坐标的背景图像中。我已在代码下方附加了所有必需的图像。
#background = 800x400
#red,blue,green = 120x48
background = Image.open('background.png')
red = Image.open('red.png')
blue = Image.open('blue.png')
green = Image.open('green.png')
positionxred = random.randint(0, 800)
positionyred = random.randint(0, 400)
positionxblue = random.randint(0, 800)
positionyblue = random.randint(0, 400)
positionxgreen = random.randint(0, 800)
positionygreen = random.randint(0, 400)
background.paste(red, (positionxred, positionyred), red)
background.paste(blue, (positionxblue, positionyblue), blue)
background.paste(green, (positionxgreen, positionygreen), green)
background.save("test.png")
附件:
背景
红色
蓝色
绿色
测试
我的目标是,红色,蓝色,绿色的图像的区域坐标是不一样的,因为如果是这样,图像会留在彼此的顶部,如图所示连接测试图像上。
如您所见,红色,蓝色和绿色的图像尺寸为120x48,即5760单位面积。
背景图片的尺寸为400x800,总面积为320000个单位。
我需要一种方法,使用一些循环命令,使每个图像的5760面积单位不停留在另一个图像的顶部,我应该如何进行?
答案 0 :(得分:1)
所有图像不重叠时,核心部分是重试粘贴点:
from PIL import Image
import random
"""
[ref](https://www.geeksforgeeks.org/find-two-rectangles-overlap/)
"""
def is_overlap(l1, r1, l2, r2):
if l1[0] > r2[0] or l2[0] > r1[0]:
return False
if l1[1] > r2[1] or l2[1] > r1[1]:
return False
return True
background = Image.open('background.png')
paste_image_list = [Image.open('red.png'), Image.open('blue.png'), Image.open('green.png')]
alread_paste_point_list = []
for img in paste_image_list:
# if all not overlap, find the none-overlap start point
while True:
# left-top point
# x, y = random.randint(0, background.size[0]), random.randint(0, background.size[1])
# if image need in the bg area, use this
x, y = random.randint(0, max(0, background.size[0]-img.size[0])), random.randint(0, max(0, background.size[1]-img.size[1]))
# right-bottom point
l2, r2 = (x, y), (x+img.size[0], y+img.size[1])
if all(not is_overlap(l1, r1, l2, r2) for l1, r1 in alread_paste_point_list):
# save alreay pasted points for checking overlap
alread_paste_point_list.append((l2, r2))
background.paste(img, (x, y), img)
break
background.save("test.png")
# check like this, all three rectangles all not overlapping each other
from itertools import combinations
assert(all(not is_overlap(l1, r1, l2, r2) for (l1, r1), (l2, r2) in combinations(alread_paste_point_list, 2)))