为了账号安全,请及时绑定邮箱和手机立即绑定

使用Python水平组合多个图像

使用Python水平组合多个图像

SMILET 2019-09-20 15:31:50
我试图在Python中水平组合一些JPEG图像。问题我有3个图像 - 每个是148 x 95 - 见附件。我只是制作了3张相同的图像 - 这就是为什么它们是相同的。我的尝试我正在尝试使用以下代码水平加入它们:import sysfrom PIL import Imagelist_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 95for 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。题有没有办法水平连接这些图像,使test.jpg中的子图像没有显示额外的部分图像?附加信息我正在寻找一种水平连接n个图像的方法。我想一般使用这个代码所以我更愿意:如果可能的话,不要硬编码图像尺寸在一行中指定尺寸,以便可以轻松更改它们
查看完整描述

3 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

我会试试这个:


import numpy as np

import PIL


list_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 picture

imgs_comb = PIL.Image.fromarray( imgs_comb)

imgs_comb.save( 'Trifecta.jpg' )    


# for a vertical stacking it is simple: use vstack

imgs_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.jpg

//img1.sycdn.imooc.com//5d8481170001651c04990743.jpg

Test2.jpg

//img1.sycdn.imooc.com//5d8481180001602501880268.jpg

Test3.jpg

//img1.sycdn.imooc.com//5d84811b00014f0002140318.jpg

Trifecta.jpg:

//img1.sycdn.imooc.com//5d84811d0001639605640268.jpg

Trifecta_vertical.jpg

//img1.sycdn.imooc.com//5d8481200001052c01880804.jpg

查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 734 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信