gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:58:26 24 4
gpt4 key购买 nike

我正在尝试使用 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")

以下是要测试的图片:

image1 , image2 , image3

我需要将图片对角排列以适合最终的 900 x 1200 像素大小的白色背景图片。也许它们需要缩小一点尺寸并合身?至少这是我在 Photoshop 中手动完成的过程(耗时)。

有时需要 2 张图片,有时可能是 4 或 5 张。

Final desired result

最佳答案

这应该可以完成工作:

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

编辑:我添加了用于调整大小和填充的代码,以便输出完全符合您想要的大小(同时保持纵横比)。

关于python - 如何使用Python将多张图片对角线合并为一张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56038056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com