Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two matrices in Python OpenCV?

Tags:

python

opencv

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

I am looking for a pre-existing method that will perform 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
like image 835
Flimm Avatar asked Jan 29 '13 09:01

Flimm


People also ask

How do you concatenate in OpenCV?

To concatenate images vertically and horizontally with Python, cv2 library comes with two functions as: hconcat(): It is used as cv2. hconcat() to concatenate images horizontally.

What is image concatenation?

Concatenate image means joining of two images. We can merge any image whether it has different pixels, different image formats namely, 'jpeg', 'png', 'gif', 'tiff', etc. In python, we can join two images using the Python image library also known as the pillow library.


2 Answers

If you are using cv2, (you will get Numpy support then), you can use 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))
like image 50
Abid Rahman K Avatar answered Oct 02 '22 15:10

Abid Rahman K


You should use cv2. Legacy uses cvmat. But numpy arrays are really easy to work with.

As suggested by @abid-rahman-k, you can use hstack(which I didn't know about) so I had 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

Let's assume that height of img0 is greater than height of image

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)
like image 27
Froyo Avatar answered Oct 02 '22 13:10

Froyo