Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python OpenCV中连接两个矩阵?_Python_Opencv - Fatal编程技术网

如何在Python OpenCV中连接两个矩阵?

如何在Python OpenCV中连接两个矩阵?,python,opencv,Python,Opencv,如何将两个矩阵连接成一个矩阵?结果矩阵的高度应与两个输入矩阵的高度相同,其宽度应等于两个输入矩阵的宽度之和 我正在寻找一种预先存在的方法,它将执行与此代码等效的操作: 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

如何将两个矩阵连接成一个矩阵?结果矩阵的高度应与两个输入矩阵的高度相同,其宽度应等于两个输入矩阵的宽度之和

我正在寻找一种预先存在的方法,它将执行与此代码等效的操作:

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
如果您使用的是cv2,(那么您将获得Numpy支持),您可以使用Numpy函数
np.hstack((img1,img2))
来完成此操作

例如:


您应该使用
cv2
。Legacy使用cvmat。但是numpy阵列确实很容易使用

正如所建议的,您可以使用hstack(我不知道),所以我使用了这个

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
但是,如果您想使用遗留代码,这应该会有所帮助

假设img0的高度大于图像的高度

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)

我知道这个问题很老了,但我偶然发现了它,因为我想连接二维数组(而不仅仅是一维数组)

np.hstack
不会执行此操作

假设您有两个仅为二维的
640x480
图像,请使用
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

如果使用矩阵,则应使用
cv2
。它对
numpy
数组的内置支持使这类问题成为一个简单的问题。我认为这应该是一个新的自我回答问题,因为这个答案与原始问题无关
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