python - 如何垂直合并两个图像?

标签 python numpy python-imaging-library

如何使用 Python 和 PIL 库垂直合并两个图像?我尝试这样做:

images_list = ['pil_text.png','pic.jpeg']
imgs = [ Image.open(i) for i in images_list ]
min_img_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]

img_merge = np.vstack( (np.asarray( i.resize(min_img_shape,Image.ANTIALIAS) ) for i in imgs ) )
img_merge = Image.fromarray( img_merge)
img_merge.save( 'terracegarden_v.jpg' )

但是我在底部的图像被压扁了。

最佳答案

请注意,除非您出于某种原因想要使用更大的脚本,否则不需要在此过程中涉及 numpy。

from PIL import Image
images_list = ['pil_text.png', 'pic.jpeg']
imgs = [Image.open(i) for i in images_list]

# If you're using an older version of Pillow, you might have to use .size[0] instead of .width
# and later on, .size[1] instead of .height
min_img_width = min(i.width for i in imgs)

total_height = 0
for i, img in enumerate(imgs):
    # If the image is larger than the minimum width, resize it
    if img.width > min_img_width:
        imgs[i] = img.resize((min_img_width, int(img.height / img.width * min_img_width)), Image.ANTIALIAS)
    total_height += imgs[i].height

# I have picked the mode of the first image to be generic. You may have other ideas
# Now that we know the total height of all of the resized images, we know the height of our final image
img_merge = Image.new(imgs[0].mode, (min_img_width, total_height))
y = 0
for img in imgs:
    img_merge.paste(img, (0, y))

    y += img.height
img_merge.save('terracegarden_v.jpg')

关于python - 如何垂直合并两个图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53876007/

相关文章:

python - 包装器的 Gensim 模块属性错误

python - 如何在 Apache Beam (Python) 中通过键在静态查找表上以流模式加入 PCollection

python - 并行化我的 python 程序

Python 3.4 与 numpy、scipy 和 matplotlib 的兼容性

python - jax 困惑 - 最佳实践是什么?

python - 使用 Python 的 PIL,如何增强图像的对比度/饱和度?

python - 类型错误 : unbound method "method name" must be called with "Class name" instance as first argument (got str instance instead)

python - 使用 np.random 生成值

python - PIL仅保存第一张图像

python - 无法将图像保存到 django 模型