前言:帮朋友做一个心理学测试程序的时候遇到了这个需求,需要把九张图片拼凑成一张图片,搜了下居然没找到合适的轮子,倒是只有把一张图裂成九张的,真·裂开。于是搞了个简单的九宫格图片合并,把之前也是用PIL做的十字注视点图片拿来做示例,最终九宫格图片尺寸为900*900,若有需要,请自行调参。
##### 相关库:PIL
##### 思路:先创建一张黑底图片,将目标九张图片resize()后按照尺寸规格依次paste()到黑底图片上,最后若九宫格图片不规整(如有多余黑边),则使用crop()进行简单裁剪(取巧做法),
##### 先上源码:
from PIL import Image, ImageDraw
def cross():
image = Image.new(mode="RGB", size=(200, 200), color='white')
draw = ImageDraw.Draw(image)
draw.line((95, 100, 105, 100), 'black')
draw.line((100, 95, 100, 105), 'black')
image = image.resize((500, 500), )
image.save('./pictures/cross.jpg')
def fill_image():
img_list = []
cross()
for i in range(9):
img = Image.open('./pictures/cross.jpg')
img_list.append(img)
new_image = Image.new(mode="RGB", size=(1000, 1000), color='black')
order=[]
for i in range(3):
for j in range(3):
order.append([i,j])
print(order)
num=-1
p_x,p_y=0,0
for i in range(3):
p_y=0
for j in range(3):
num+=1
img_x = img_list[num].resize((300, 300),Image.ANTIALIAS)
x=order[num][0]*300+p_x
y=order[num][1]*300+p_y
new_image.paste(img_x, (y,x))
p_y += 5
p_x += 5
new_image=new_image.crop((0,0,900,900))
new_image_name='./pictures/Squared_Pictures'+'.jpg'
new_image.save(new_image_name)
new_image.show()
print('九宫格图片创建完毕')
return new_image_name
fill_image()
效果展示
十字注视点:
九宫格图: