使用Python水平组合多个图像

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


问题

我有3个图像 - 每个是148 x 95 - 见附件。我只是制作了3张相同的图像 - 这就是为什么它们是相同的。

http://img2.mukewang.com/5d8480810001204301480095.jpg

我的尝试

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


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。

http://img2.mukewang.com/5d84808800017ea004440095.jpg

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


附加信息

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


如果可能的话,不要硬编码图像尺寸

在一行中指定尺寸,以便可以轻松更改它们


SMILET
浏览 735回答 3
3回答

繁星点点滴滴

我会试试这个:import numpy as npimport PILlist_im = ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']imgs    = [ PIL.Image.open(i) for i in list_im ]# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )# save that beautiful pictureimgs_comb = PIL.Image.fromarray( imgs_comb)imgs_comb.save( 'Trifecta.jpg' )    # for a vertical stacking it is simple: use vstackimgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )imgs_comb = PIL.Image.fromarray( imgs_comb)imgs_comb.save( 'Trifecta_vertical.jpg' )只要所有图像具有相同的种类(所有RGB,所有RGBA或所有灰度),它都应该工作。确定这是多行代码的情况应该不难。这是我的示例图像,结果如下:Test1.jpgTest2.jpgTest3.jpgTrifecta.jpg:Trifecta_vertical.jpg
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python