Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python将多张图片对角合并为一张图片_Python_Numpy_Image Processing - Fatal编程技术网

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

如何使用Python将多张图片对角合并为一张图片,python,numpy,image-processing,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"

我正在尝试使用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")
以下是要测试的图片:

,

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

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


这应该可以完成以下工作:

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

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

白色背景将覆盖在生成的图像中。您应该使用带有透明背景的svg图像。有趣的是…那么我必须将png(透明)转换为svg吗?这就是你想说的?我说第一步是在覆盖它们之前使背景透明,否则,你只会得到一张前毛衣的照片和许多白色边框。对不起,为什么?我的文件已经是透明的png文件了。对我来说,最难的部分是找出如何像最后一张照片那样排列它们。我的坏朋友当时认为背景是白色的。太棒了!!!我正要问你这个问题,因为我试着用了4张图片,最终的文件超过了900x1200!你是我的英雄!我注意到在你更新你的答案后,最终的结果变得非常尖锐:(你知道它可能是什么吗?重试,我添加了双三次插值,默认值是最近邻。有一些库支持PSD(我刚刚在谷歌上搜索了它)在这里我没有任何经验。考虑使用TIFF,它也支持层。在代码25中找到了一个小错误。PiL.IIGIOBIUBICIC——删除了PIL。-工作得很好!再次感谢!是的,我有一个额外的导入。我修复了。谢谢。