2013-01-29 3 views
7

어떻게 두 개의 행렬을 하나의 행렬로 연결합니까? 결과 행렬은 두 입력 행렬과 동일한 높이를 가져야하며, 그 폭은 두 입력 행렬의 폭의 합과 같습니다. 이 코드의 상당 수행하는 기존의 방법을 찾고 있어요Python OpenCV에서 두 행렬을 어떻게 연결합니까?

: 당신이 CV2를 사용하는 경우

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 
+0

매트릭스로 작업하는 경우 'cv2'를 사용해야합니다. 'numpy' 배열을위한 내장 된 지원은 이런 종류의 질문을 한 줄짜리로 만듭니다. – casper

답변

9

, 당신은 NumPy와 기능 np.hstack((img1,img2))을 사용할 수 있습니다 (당신은 그 NumPy와 지원을받을 것) 이것을하기 위해.

예를 들면 :

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

당신은 cv2를 사용해야합니다. 레거시는 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) 
1

의 높이보다 큰 가정 해 보자 도움이 될 것입니다, 두 차원 (하나의 차원을 연결하는 것만이 아님) 인 배열을 연결하려고했기 때문에 우연히 발견되었습니다.

np.hstack이 작업을 수행하지 않습니다.

640x480 이미지가 2 차원 인 경우를 가정하면 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 
+0

이 답변은 원래 질문과 관련이 없으므로 새로운 자체 답변 질문이어야한다고 생각합니다. – VMAtm

관련 문제