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

10 投票
4 回答
13866 浏览
提问于 2025-04-17 14:01

我想知道怎么把两个矩阵合并成一个矩阵。合并后的矩阵高度要和这两个输入矩阵一样,而宽度则是这两个输入矩阵宽度的总和。

我在寻找一个已经存在的方法,可以实现和下面这段代码一样的功能:

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

4 个回答

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

3

你应该使用OpenCV。老旧的代码用的是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)
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))

撰写回答