Create a Collage of Images with the help of NumPy and Python-OpenCV(CV2)

In this article, we will see how we can make the collage of images with the help of NumPy and python-opencv(cv2)?
Submitted by Abhinav Gangrade, on August 14, 2020

Modules Used

In this article, we will use NumPy and python-opencv(cv2) libraries.

NumPy

NumPy is a python library that will help us to solve the problems based on scientific computation and to store the data of the same data types. 

Downloading NumPy

  • General way: pip install NumPy
  • Pycharm Users: Go to the project interpreter -> click on + button -> download NumPy.

python-opencv(cv2)

python-opencv(cv2)(Open source computer vision) is a python library that will help us to solve the problems related to computer vision.

Downloading python-opencv(cv2)

  • General way: pip install python-opencv
  • Pycharm users: Go to the project interpreter -> click on + button -> download the module.

Problem statement (What we will actually do in this tutorial)?

In this tutorial, we will try to join images with the help of NumPy functions and we will use python-opencv(cv2) for reading and getting the data of the images. We will create a horizontal stack of images then after that, we will join them in a vertical stack of images.

Note: We have taken only 4 Images for collage.

Algorithm

Let us see some of the algorithm/functions that we will use in this article:

  1. np.hstack([<image1>,<image2>]): It will create a horizontal stack of images.
  2. np.vstack([<image1>,<image2>]): It will create a vertical stack of images.
  3. cv2.resize(<image>,(<area we want upto>)): It will resize the image.

Python program to create a collage of images

# importing the modules
import cv2
import numpy as np

# read all the images
# we are going to take 4 images only
image1=cv2.imread("index1.png")
image2=cv2.imread("index2.jpeg")
image3=cv2.imread("index3.jpeg")
image4=cv2.imread("images.png")

# make all the images of same size 
#so we will use resize function
image1=cv2.resize(image1,(200,200))
image2=cv2.resize(image2,(200,200))
image3=cv2.resize(image3,(200,200))
image4=cv2.resize(image4,(200,200))

# Now how we will attach image with other image
# we will create a horizontal stack of images
# then we will add it to the vertical stack
# let the horizontal pair be (image1,image2)
# and (image3,image4)
# we will use numpy stack function
Horizontal1=np.hstack([image1,image2])
Horizontal2=np.hstack([image3,image4])

# Now the horizontal attachment is done
# noe vertical attachment
Vertical_attachment=np.vstack([Horizontal1,Horizontal2])

# Show the final attachment
cv2.imshow("Final Collage",Vertical_attachment)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Collage of Images

This is the Final Image that we have created. In this way, we can create a collage.

All Python NumPy Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.