Combining Two Images with OpenCV Combining Two Images with OpenCV python python

Combining Two Images with OpenCV


For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.

To stack vertically (img1 over img2):

vis = np.concatenate((img1, img2), axis=0)

To stack horizontally (img1 to the left of img2):

vis = np.concatenate((img1, img2), axis=1)

To verify:

import cv2import numpy as npimg1 = cv2.imread('img1.png')img2 = cv2.imread('img2.png')vis = np.concatenate((img1, img2), axis=1)cv2.imwrite('out.png', vis)

The out.png image will contain img1 on the left and img2 on the right.


For those who are looking to combine 2 color images into one, this is a slight mod on Andrey's answer which worked for me :

img1 = cv2.imread(imageFile1)img2 = cv2.imread(imageFile2)h1, w1 = img1.shape[:2]h2, w2 = img2.shape[:2]#create empty matrixvis = np.zeros((max(h1, h2), w1+w2,3), np.uint8)#combine 2 imagesvis[:h1, :w1,:3] = img1vis[:h2, w1:w1+w2,:3] = img2


import numpy as np, cv2img1 = cv2.imread(fn1, 0)img2 = cv2.imread(fn2, 0)h1, w1 = img1.shape[:2]h2, w2 = img2.shape[:2]vis = np.zeros((max(h1, h2), w1+w2), np.uint8)vis[:h1, :w1] = img1vis[:h2, w1:w1+w2] = img2vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)cv2.imshow("test", vis)cv2.waitKey()

or if you prefer legacy way:

import numpy as np, cvimg1 = cv.LoadImage(fn1, 0)img2 = cv.LoadImage(fn2, 0)h1, w1 = img1.height,img1.widthh2, w2 = img2.height,img2.widthvis = np.zeros((max(h1, h2), w1+w2), np.uint8)vis[:h1, :w1] = cv.GetMat(img1)vis[:h2, w1:w1+w2] = cv.GetMat(img2)vis2 = cv.CreateMat(vis.shape[0], vis.shape[1], cv.CV_8UC3)cv.CvtColor(cv.fromarray(vis), vis2, cv.CV_GRAY2BGR)cv.ShowImage("test", vis2)cv.WaitKey()