Life2Coding
Combine Several Images Horizontally with Padding using OpenCV Python

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:

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 horizontally using OpenCV python.

Documentation:

imread()

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

Loads an image from a file.

Parameters
filename Name of file to be loaded.
flags Flag that can take values of cv::ImreadModes

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

Parameters
winname Name of the window.
mat Image to be shown.

imwrite()

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

Saves an image to a specified file.

Parameters
filename Name of the file.
img Image to be saved.
params Format-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.

Parameters
delay Delay 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_height between all the images
  • Also need to calcuate the max width by adding all the images’ width
  • Then need to define the new image height using the max height and total width
  • 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_horizontally(image_names,padding=20):
    images = []
    max_height = 0  # find the max height of all the images
    total_width = 0  # the total width of the images (horizontal stacking)

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

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


        if image_height > max_height:
            max_height = image_height

        # add all the images widths
        total_width += image_width

    # 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((max_height, (len(image_names)-1)*padding+ total_width, 3), dtype=np.uint8)

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

    return final_image



if __name__ == '__main__':

    image_names = ['./opencv.jpg','./python.jpg','./windows.jpg']

    final_image=combine_horizontally(image_names,padding=0)
    cv2.imshow('out',final_image)
    cv2.imwrite('horizontal.PNG',final_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Output:

5dbfc7982dc80 Combine Several Images Horizontally with Padding using OpenCV Python
life2coding_icon [] Combine Several Images Horizontally with Padding using OpenCV Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.