Merging Images

Merging images is process of composing/re-composing an image from its channels or other images. It is often done when individual channels need to be processed separately and combined afterwards into the original dimension. It can also be used in masking/green screen effects. Merging can be done through numpy operations or the opencv.merge() method.

import cv2
import numpy as np
import matplotlib.pyplot as plt

# reading the image
bear = cv2.imread('bear.jpg', cv2.IMREAD_COLOR)
bear = cv2.cvtColor(bear, cv2.COLOR_BGR2RGB)

# splitting an image 
red, green, blue = bear[:, :, 0], bear[:, :, 1], bear[:, :, 2]
red.shape, green.shape, blue.shape
((427, 640), (427, 640), (427, 640))

Merging an Image with cv2.merge()

The merge function takes an array of channels with equal dimension and returns the merged image

merged_cv = cv2.merge([red, green, blue])

plt.imshow(merged_cv)
plt.axis('off')
Merged image with opencv

Implementation in Numpy

merged_np = np.zeros((red.shape[0], red.shape[1], 3), dtype='uint8')
merged_np[:, :, 0] = red
merged_np[:, :, 1] = green
merged_np[:, :, 2] = blue

merged_cv.shape, merged_np.shape
((427, 640, 3), (427, 640, 3))