How to best create a new image out of existing images in openCV
When images are read in OpenCV's Python API, you get Numpy arrays. Numpy has vstack()
and hstack()
functions, which you can use to stack arrays (images) vertically and horizontally.
Let's open up two images with OpenCV:
import cv2
import numpy as np
knight = cv2.imread('knight.jpg', cv2.IMREAD_GRAYSCALE)
To use stacking in numpy, there are restriction on the image dimensions depending on the stackng axis (vertical/horizontal), so for this image, I will use cv2.resize()
to get the right dimensions
queen = cv2.imread('queen.jpg', cv2.IMREAD_GRAYSCALE)
queen = cv2.resize(queen, (525, 700))
Let's make a first column by stacking 2 Knights
col_1 = np.vstack([knight, knight]) # Simply put the images in the list
# I've put 2 knights as example
Now let's make a second column with 2 Queens
col_2 = np.vstack([queen, queen])
Let's put those two columns together, but this time we'll use hstack()
for that
collage = np.hstack([col_1, col_2]
Et voila, a collage of 2 x 2 which you can adapt to your needs. Note that the images passed in the stacking do need to be identical or anything, you can pass in any list of images, as long as you respect the dimensions.