Python combine two images vertically

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Then the output will be visualized along with the comparisons.

We will also discuss the basic of image processing and provide the detail explanation related to the OpenCV functions.

Requirements:

  • OpenCV 3.4+
  • Python 3.6+
  • Numpy
  • Image, Webcam or Video input
  • Documentation Source: OpenCV Official Documentation

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV with Python 3

Goals:

The goal is to combine or merge multiple images vertically using OpenCV python.

Documentation:

imread()

retval=cv.imread(filename[, flags])

Loads an image from a file.

ParametersfilenameName of file to be loaded.flagsFlag that can take values of cv::ImreadModes

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

ParameterswinnameName of the window.matImage to be shown.

imwrite()

retval=cv.imwrite(filename, img[, params])

Saves an image to a specified file.

ParametersfilenameName of the file.imgImage to be saved.paramsFormat-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, … .) see cv::ImwriteFlags

waitKey()

retval=cv.waitKey([, delay])

Waits for a pressed key.

ParametersdelayDelay in milliseconds. 0 is the special value that means “forever”.

destroyAllWindows()

None=cv.destroyAllWindows()

Destroys all of the HighGUI windows.

Steps:

  • Open the list of images using cv2.imread()
  • Get the max_width between all the images
  • Also need to calcuate the max height by adding all the images’ height
  • Then need to define the new image height using the max width and total height
  • Also padding is added between the images which can be adjusted easily
  • Display the combined image using cv2.imshow()
  • Save the output image using cv2.imwrite()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np

def combine_vertically(image_names,padding=40):
    images = []
    max_width = 0  # find the max width of all the images
    total_height = 0  # the total height of the images (vertical stacking)

    for name in image_names:
        # open all images and find their sizes
        img=cv2.imread(name)
        images.append(img)

        image_width=img.shape[1]
        image_height=img.shape[0]

        if image_width > max_width:
            max_width = image_width

        #add all the images heights
        total_height += image_height



    # create a new array with a size large enough to contain all the images
    # also add padding size for all the images except the last one
    final_image = np.zeros((total_height+(len(image_names)-1)*padding,max_width,3),dtype=np.uint8)

    current_y = 0 # keep track of where your current image was last placed in the y coordinate
    for image in images:
        # add an image to the final array and increment the y coordinate
        height = image.shape[0]
        width = image.shape[1]
        final_image[current_y:height+current_y,:width,:] = image
        # add the padding between the images
        current_y += height+ padding
    return final_image




if __name__ == '__main__':

    image_names = ['./opencv.jpg','./python.jpg','./windows.jpg']
    final_image=combine_vertically(image_names,padding=0)
    cv2.imshow('out',final_image)
    cv2.imwrite('vertical.PNG',final_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Output:

Life2Coding

Technology Related Blog at Life2Coding

Feel free to contact us for your any kind of technical problems. We are here to help you.

Latest posts by Life2Coding (see all)

  • How to Create a RGB Color Picker for Images using OpenCV Python - 22 April, 2022
  • Combine Several Images Vertically with Padding using OpenCV Python - 21 April, 2022
  • Combine Several Images Horizontally with Padding using OpenCV Python - 21 April, 2022

  • Create a Black Background Image using OpenCV in Python
  • Load Webcam Video using OpenCV in Python
  • Extract Each Frame from a Video File using OpenCV in Python

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Skype (Opens in new window)

computer vision, Image Processing, machine learning, opencv python, python image processing, robotics, video processing

How do you combine images vertically in Python?

Combine two images vertically Once the width of both images are same, then we can use the np. concatenate function of Numpy with axis as 0. The first parameter will be the top image and the second parameter will be the bottom image. Both images should be loaded as Numpy array which can be done using np.

How to combine 2 images into one python?

Merging two images Create an empty image using the Image. new() function. Paste the images using the paste() function. Save and display the resultant image using the save() and show() functions.

How to add two images of different size in OpenCV Python?

Step 1: Import the libraries and read the image. The images that we are using for this recipe are as follows. import cv2. ... .
Step 2: Compare and alter the sizes. To add two images, the shape of those two images must be equal. ... .
Step 3: Add images. Now let us add these to images using the cv2..