Join images vertically or horizzontally

This code will join images vertically or horizzontally. This could be useful, for example, to make spreadsheet from single images that you could use in an animation for a videogame. You could also use it to show slides in a blog and you want to unite them (I think vertically), so that you use one file. I don’t know, if you are here, you thought to a reason to do it, so it’s not necessary that I explain it to you. Let’s see how to do it.

To join vertically

This in case you called the file joinimages.py, of course. You can choose other names and you will change the command below using the name you choose (sorry for being obvious, but so it is).

In the cmd you will write (don’t forget a space before the final v or h.

python joinimages.py v

To join horizzontally

python joinimages.py h

The code

import numpy as np
from PIL import Image
import glob
import sys


print("To join vertically: py -m join v")

print("To join horizzontally: py -m join h")


def join():
    list_im = glob.glob("*.png")
    imgs = [Image.open(i) for i in list_im]
    # resize images to the smallest one
    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
    if sys.argv[1] == "v":
        # 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 = Image.fromarray(imgs_comb)
        imgs_comb.save('vertical.png')

    else:
        imgs_comb = Image.fromarray(imgs_comb)
        imgs_comb.save('horizontal.png')


join()
Example of joining 8 images
Joining 8 images

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.