简体   繁体   English

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

[英]How to merge multiple pictures diagonally into a single one using Python

I'm trying to merge multiple images diagonally into a single one using Python. 我正在尝试使用Python将多个图像对角合并为一个图像。 I checked a lot of questions but didn't find something similar to my need. 我检查了很多问题,但没有找到与我的需求相似的东西。

All I can do right now is a simple merge of files on top of each other: 我现在所能做的就是将文件简单地合并在一起:

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")

Here are the pictures to test : 这是要测试的图片:

image1 , image2 , image3 image1image2image3

I need the pictures to be arranged diagonally to fit into a final 900 x 1200 px size picture with white Background. 我需要将图片按对角线排列,以适合具有白色背景的最终900 x 1200 px尺寸的图片。 Probably they need to be sized down a bit and fit ? 可能需要缩小尺寸并适合它们吗? At least that's the process I am doing in Photoshop, manually (time consuming). 至少那是我在Photoshop中手动执行的过程(非常耗时)。

Sometimes there's 2 pictures to fit, sometimes could be 4 or 5. 有时有2张图片适合,有时可能是4张或5张。

最终预期结果

This should do the job: 这应该做的工作:

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()

EDIT: I added the code for resizing and padding such that the output is exactly of your wanted size (whilst maintaining the aspect ratio). 编辑:我添加了用于调整大小和填充的代码,以便输出恰好是您想要的大小(同时保持宽高比)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM