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

10

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

我正在寻找一个现成的方法,可以执行与此代码等效的操作:

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数组,可以将这些问题简化成一行代码。 - hjweide
你也可以使用 cv2.vconcat()cv2.hconcat(),参见这里:https://dev59.com/fWUq5IYBdhLWcg3wV_Ai#72177160 - Jeru Luke
4个回答

13
如果您正在使用OpenCV(那么您将得到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))

3

您应该使用OpenCV。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)

2

OpenCV内置了用于垂直/水平拼接图像的函数:

  • cv2.vconcat()
  • cv2.hconcat()

注意:在拼接时,图像必须具有相同的尺寸,否则您将遇到类似于error: (-215:Assertion failed)....的错误消息。

代码:

img = cv2.imread('flower.jpg', 1)

# concatenate images vertically    
vertical_concat = cv2.vconcat([img, img])

enter image description here

# concatenate images horizontally
horizontal_concat = cv2.hconcat([img, img])

enter image description here


1
我知道这个问题很久了,但我偶然发现它是因为我想连接二维数组(而不仅仅是在一个维度上连接)。
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

1
我认为应该新建一个自问自答的问题,因为这个回答与原问题无关。 - VMAtm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接