python - 使用Python水平组合多个图像

标签 python python-3.x python-imaging-library python-2.x paste

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

问题

我有 3 张图片 - 每张图片都是 148 x 95 - 请参阅附件。我刚刚制作了同一张图像的 3 个副本 - 这就是它们相同的原因。

enter image description here enter image description here enter image description here

我的尝试

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

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 的输出。

enter image description here

问题

有没有办法水平连接这些图像,使得 test.jpg 中的子图像不会显示额外的部分图像?

其他信息

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

  • 如果可能,不要对图像尺寸进行硬编码
  • 在一行中指定尺寸,以便轻松更改

最佳答案

你可以这样做:

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

Test1.jpg

Test2.jpg

Test2.jpg

Test3.jpg

Test3.jpg

test.jpg

enter image description here

<小时/>

嵌套的 for i in xrange(0,444,95): 将每个图像粘贴 5 次,间隔 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('new_' + elem + '.jpg')

enter image description here enter image description here enter image description here

关于python - 使用Python水平组合多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227466/

相关文章:

Python sqlite3 和并发

Python 无法在 Ubuntu 14.04 上运行(可信) - 无法导入标准库

python - 如何将python程序完全转化为exe文件?

Python-变量作用域

python - 在 python Pillow 中使用列表生成图像不起作用

python - 如何获取 lxml.etree 的父标签属性,如 'KEY' 、 'NAME' 、 Python 3.6

python - 根据 n 个连续条目替换列中的值

python-3.x - 如何解析 python 3 中的 gmail messages.get() 批处理响应

unicode - 使用PIL绘制多语言文本

python - 如何在 Python 中将 .EPS 文件保存为透明的 PNG