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

2024-06-07 07:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

Tags: 方法代码infor宽度高度res矩阵
3条回答

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

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支持),那么您可以使用Numpy函数np.hstack((img1,img2))来执行此操作。

例如:

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))

你应该使用cv2。Legacy使用cvmat。但是numpy数组非常容易使用。

正如@abid-rahman-k所建议的,您可以使用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)

相关问题 更多 >

    热门问题