I have several images which I want to aggregate in a new image 8 image per column, 5 per row side by side with openCV in Python.
Curiously, I did not find an answer which directly addresses this question. From my spare knowledge on openCV, I would now count the width and height of the image to which the existing images should be copied, create a numpy Array with these images and change the values of the corresponding regions of Pinterest to values of each image.
Would this procedure work and more important isn't there an easier solution for this problem which haven't found?
The image pasting is a process of overlaying one image on top of the other. To successfully apply this process in OpenCV we need to select Region of Interest (ROI) in the first image, and then apply masking and some logical operations to overlay second image over the first image.
Like before, we start by importing the cv2 module, followed by reading both images and resizing them to be 400×400. We will then display the second image in a window called “blend“. It will be the one we will use every time we update the weights to display the resulting image.
We can use the concatenate() function of NumPy to concatenate the matrices of the images along different axes. For example, let's use the zeros() function of NumPy to create two images with different colors and then combine them horizontally using the concatenate() function.
OpenCV is a pre-built, open-source CPU-only library (package) that is widely used for computer vision, machine learning, and image processing applications. It supports a good variety of programming languages including Python.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With