I have 15 images (from 1 to 15). I would like to stitch these images together so that it forms one single image. What I tried so far?
import numpy as np
import PIL
from PIL import Image
import os
filenames = [os.path.abspath(os.path.join(directory, p)) for p in os.listdir(directory) if p.endswith(('jpg', 'png'))]
imgs = [PIL.Image.open(i) for i in filenames]
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 ) )
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'stitched_image.jpg' )
This stitches the image horizontally and not as a perfect image. The output looks like the following:
But the desired output should be:
How do I do that?
These are stitched together horizontally because you have stuck them together with np.hstack()
when you actually want to hstack
only three at a time into rows and then vstack
them together vertically. Replacing that one line with the below should do what you need.
img_rows = []
for min_id in range(0, 15, 3):
img_row = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs[min_id: min_id+3] ) )
img_rows.append(img_row)
imgs_comb = np.vstack( ( i for i in img_rows ) )