本文介绍了使用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']
new_im = Image.new('RGB', (444,95)) #creates a new empty image, RGB mode, and size 444 by 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 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水平合并多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 04:33