Reputation: 81
I would like to merge all pictures in a folder and have them stacked, appended horizontally.
import os
from PIL import Image
allfiles = os.listdir(os.getcwd())
imlist =[filename for filename in allfiles if filename[-4:] in [".png", ".PNG"]]
N = len(imlist)
w, h = Image.open(imlist[0]).size
total_width = w * N
max_height = h
new_im = Image.new('RGB', (total_width, max_height))
for i in range(1,N):
img = Image.open(imlist[i])
offset = 0
appendedimages.paste(img, (x_offset,0))
offset += img.size[0]
appendedimages.save('test.jpg')
It seems, that using this, it only displays the last image. Does someone know why that happens?
I have also tried
import cv2
import os
import numpy as np
allfiles = os.listdir(os.getcwd())
imlist =[filename for filename in allfiles if filename[-4:] in [".png", ".PNG"]]
N = len(imlist)
for i in range(1,N):
img = cv2.imread(imlist[i])
horizontalAppendedImg = np.hstack(img)
cv2.imshow('Horizontal Appended', horizontalAppendedImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
But that also doesn't work.
Can anyone help me with this? Or is there a simpler solution to this?
Upvotes: 0
Views: 973
Reputation: 1488
images are numpy arrays. As long as they have the same dimensions, you can np.hstack
them.
imlist =[cv2.imread(filename) for filename in allfiles if filename[-4:] in [".png", ".PNG"]]
concat_img = np.hstack(imlist)
cv2.imshow('Horizontal Appended', concat_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation:
np.arrays
np.hstack()
to concatenate all images along the horizontal dimension. You could use more general concatenation tools with np.concatenate()
or np.stack()
if you run into issues.Upvotes: 2