Ask Your Question

Revision history [back]

Since images are numpy arrays in OpenCV, we could use concatenate, vstack or hstack to help us achieve the task.

The comments in the code should be self explanatory but one thing to be aware of is:

1. Image Channels

A coloured and grey scale image have 3 and 1 channels respectively. You cannot just combine their respective matrices together so you need to convert one to the other. With this code, I converted the grey scale to a coloured one to facilitate the combination

2. Image Sizes

It goes without saying that this method fails when you have images of different sizes. Why? Because you are trying to perform operations on matrices of different dimensions.

PS: OpenCV also has hconcat and vconcat. I got the C++ version of it working just fine but never tested it on Python.

import cv2
import numpy as np

image = cv2.imread('pinocchio.png')
# I just resized the image to a quarter of its original size
image = cv2.resize(image, (0, 0), None, .25, .25)

grey = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Make the grey scale image have three channels
grey_3_channel = cv2.cvtColor(grey, cv2.COLOR_GRAY2BGR)

numpy_vertical = np.vstack((image, grey_3_channel))
numpy_horizontal = np.hstack((image, grey_3_channel))

numpy_vertical_concat = np.concatenate((image, grey_3_channel), axis=0)
numpy_horizontal_concat = np.concatenate((image, grey_3_channel), axis=1)

cv2.imshow('Main', image)
cv2.imshow('Numpy Vertical', numpy_vertical)
cv2.imshow('Numpy Horizontal', numpy_horizontal)
cv2.imshow('Numpy Vertical Concat', numpy_vertical_concat)
cv2.imshow('Numpy Horizontal Concat', numpy_horizontal_concat)


Horizontal Stack Horizontal Stack Results

Vertical Stack

image description