如何使用Python将多张图片对角合并为一张图片

时间:2019-05-08 09:58:50

标签: python numpy image-processing

我正在尝试使用Python将多个图像对角合并为一个图像。 我检查了很多问题,但没有找到与我的需求相似的东西。

我现在能做的就是将文件简单地合并在一起:

from PIL import Image

import numpy as np

img = Image.open("1.png")

background = Image.open("2.png")

background.paste(img, (0, 0), img)

background.save('result.png',"PNG")

这是要测试的图片:

image1image2image3

我需要将图片按对角线排列,以适合具有白色背景的最终 900 x 1200 px尺寸的图片。可能需要缩小尺寸并适合它们吗?至少那是我在Photoshop中手动执行的过程(非常耗时)。

有时候有2张照片适合,有时可能是4张或5张。

Final desired result

1 个答案:

答案 0 :(得分:2)

这应该可以完成工作:

from PIL import Image

images = ['1.png', '2.png', '3.png']

# shift between images
offset = (200, 100)
target_size = (900, 1200)

images = [Image.open(fn) for fn in images]
no_img = len(images)
image_size = [s+no_img*o for s, o in zip(images[0].size, offset)]

#create empty background
combined_image = Image.new('RGBA', image_size)

# paste each image at a slightly shifted position, start at top right
for idx, image in enumerate(images):
  combined_image.paste(image, ((no_img - idx - 1) * offset[0], idx * offset[1]), image)

# crop to non-empty area
combined_image = combined_image.crop(combined_image.getbbox())

# resizing and padding such that it fits 900 x 1200 px
scale = min(target_size[0] / combined_image.size[0], target_size[1] / combined_image.size[1])
combined_image = combined_image.resize((int(combined_image.size[0] * scale), int(combined_image.size[1] * scale)), Image.BICUBIC)
img_w, img_h = combined_image.size

finale_output = Image.new('RGB', target_size, (255, 255, 255))

offset = ((target_size[0] - img_w) // 2, (target_size[1] - img_h) // 2)
finale_output.paste(combined_image, offset, combined_image)

# display
finale_output.show()

编辑:我添加了用于调整大小和填充的代码,以便输出恰好是您想要的大小(同时保持宽高比)。