How to concatenate two matrices in Python OpenCV?

How to combine two matrices into one matrix? The resulting matrix should have the same height as the two input matrices, and its width will be equal to the sum of the width of the two input matrices.

I am looking for an existing method that will execute the equivalent of this code:

def concatenate(mat0, mat1): # Assume that mat0 and mat1 have the same height res = cv.CreateMat(mat0.height, mat0.width + mat1.width, mat0.type) for x in xrange(res.height): for y in xrange(mat0.width): cv.Set2D(res, x, y, mat0[x, y]) for y in xrange(mat1.width): cv.Set2D(res, x, y + mat0.width, mat1[x, y]) return res 
+7
source share
3 answers

If you use cv2 (then you get Numpy support), you can use the Numpy function np.hstack((img1,img2)) to do this.

eg:

 import cv2 import numpy as np # Load two images of same size img1 = cv2.imread('img1.jpg') img2 = cv2.imread('img2.jpg') both = np.hstack((img1,img2)) 
+9
source

You must use cv2 . Legacy uses cvmat. But numpy arrays are very easy to use.

As @ abid-rahman-k suggested , you can use hstack (which I did not know about), so I used this.

 h1, w1 = img.shape[:2] h2, w2 = img1.shape[:2] nWidth = w1+w2 nHeight = max(h1, h2) hdif = (h1-h2)/2 newimg = np.zeros((nHeight, nWidth, 3), np.uint8) newimg[hdif:hdif+h2, :w2] = img1 newimg[:h1, w2:w1+w2] = img 

But if you want to work with Legacy code, this should help

Suppose img0 is greater than image height

 nW = img0.width+image.width nH = img0.height newCanvas = cv.CreateImage((nW,nH), cv.IPL_DEPTH_8U, 3) cv.SetZero(newCanvas) yc = (img0.height-image.height)/2 cv.SetImageROI(newCanvas,(0,yc,image.width,image.height)) cv.Copy(image, newCanvas) cv.ResetImageROI(newCanvas) cv.SetImageROI(newCanvas,(image.width,0,img0.width,img0.height)) cv.Copy(img0,newCanvas) cv.ResetImageROI(newCanvas) 
+3
source

I know this question is old, but I stumbled upon it because I was looking for concatenation of arrays that are two dimensions (and not just concatenation in 1 dimension).

np.hstack will not do this.

Assuming you have two 640x480 images that are just used by two dimensions, use dstack .

 a = cv2.imread('imgA.jpg') b = cv2.imread('imgB.jpg') a.shape # prints (480,640) b.shape # prints (480,640) imgBoth = np.dstack((a,b)) imgBoth.shape # prints (480,640,2) imgBothH = np.hstack((a,b)) imgBothH.shape # prints (480,1280) # = not what I wanted, first dimension not preserverd 
+1
source

All Articles