stitch images together in python

我怕爱的太早我们不能终老 提交于 2019-12-06 10:04:57

Try this (explanation in comments):

from PIL import Image
from os import listdir, path

space_between_row = 10
new_image_path = 'result.jpg'
im_dirs = ['images/1', 'images/2']

# get sorted list of images
im_path_list = [[path.join(p, f) for f in sorted(listdir(p))] for p in im_dirs]

# open images and calculate total widths and heights
im_list = []
total_width = 0
total_height = 0
for path_list in im_path_list:
    images = list(map(Image.open, path_list))
    widths, heights = zip(*(i.size for i in images))
    total_width = max(total_width, sum(widths))
    total_height += max(heights)
    im_list.append(images)

# concat images
new_im = Image.new('RGB', (total_width, total_height))
y_offset = 0
for images in im_list:
    x_offset = 0
    max_height = 0
    for im in images:
        new_im.paste(im, (x_offset, y_offset))
        x_offset += im.size[0]
        max_height = max(im.size[1], max_height)
    y_offset = y_offset + max_height + space_between_row

# show and save
new_im.show()
new_im.save(new_image_path)

Install ImageMagick, then tell it where your two directories are.

#!/usr/bin/python3
##=========================================================
##  required  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##
##  imagemagick.org/script/download.php
##
##=========================================================
##  libs  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import subprocess as sp

##=========================================================
##  vars  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

offset  = 2                    ##  pixel gap between images
color  = '#000000'        ##  background color to fill gaps

dir1  = '/home/me/Pictures/topRow/'

dir2  = '/home/me/Pictures/bottomRow/'

##  note: windows dirs use double backslashes
##  'C:\\Users\\me\\Pictures\\topRow\\'
##=========================================================
##  script  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

row1args  = ['convert', '+smush', offset, '-background', color, dir1 + '*.png', 'row1.png']
row2args  = ['convert', '+smush', offset, '-background', color, dir2 + '*.png', 'row2.png']
merge  = ['convert', '-smush', offset, '-background', color, 'row*.png', 'merged.png']

##=========================================================
##  main  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

sp .call(row1args)
sp .call(row2args)
sp .call(merge)

##=========================================================
##  eof  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!