用 Python 将多个图像水平组合 [英] Combine several images horizontally with Python

查看:36
本文介绍了用 Python 将多个图像水平组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中水平组合一些 JPEG 图像.

I am trying to horizontally combine some JPEG images in Python.

我有 3 张图片 - 每张都是 148 x 95 - 见附件.我刚刚复制了同一张图片的 3 个副本 - 这就是为什么它们是一样的.

I have 3 images - each is 148 x 95 - see attached. I just made 3 copies of the same image - that is why they are the same.

我正在尝试使用以下代码水平连接它们:

I am trying to horizontally join them using the following code:

import sys
from PIL import Image

list_im = ['Test1.jpg','Test2.jpg','Test3.jpg']

# creates a new empty image, RGB mode, and size 444 by 95
new_im = Image.new('RGB', (444,95))

for elem in list_im:
    for i in xrange(0,444,95):
        im=Image.open(elem)
        new_im.paste(im, (i,0))
new_im.save('test.jpg')

然而,这会产生附加为 test.jpg 的输出.

However, this is producing the output attached as test.jpg.

有没有办法水平连接这些图片,使得 test.jpg 中的子图片没有多余的部分图片显示?

Is there a way to horizontally concatenate these images such that the sub-images in test.jpg do not have an extra partial image showing?

我正在寻找一种水平连接 n 个图像的方法.我想一般使用此代码,所以我更愿意:

I am looking for a way to horizontally concatenate n images. I would like to use this code generally so I would prefer to:

  • 如果可能,不要硬编码图像尺寸
  • 在一行中指定尺寸以便于更改它们

推荐答案

你可以这样做:

import sys
from PIL import Image

images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
  new_im.paste(im, (x_offset,0))
  x_offset += im.size[0]

new_im.save('test.jpg')

Test1.jpg

Test2.jpg

Test3.jpg

test.jpg

嵌套 for for i in xrange(0,444,95): 将每个图像粘贴 5 次,交错间隔 95 个像素.每次外循环迭代都粘贴在前一个上.

The nested for for i in xrange(0,444,95): is pasting each image 5 times, staggered 95 pixels apart. Each outer loop iteration pasting over the previous.

for elem in list_im:
  for i in xrange(0,444,95):
    im=Image.open(elem)
    new_im.paste(im, (i,0))
  new_im.save('new_' + elem + '.jpg')

这篇关于用 Python 将多个图像水平组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆