OpenCV cv2透视变换矩阵乘法

时间:2013-10-18 09:30:03

标签: python opencv

我试图通过组合getPerspectiveTransform生成的矩阵将一系列warpPerspective组合成一个。如果我使用cv2.multiply将它们相乘,则生成的矩阵不起作用。仅进行两次转换的示例:

src = np.array([[0,0],[0,480],[640,480],[640,0]],np.float32)
dst = np.array([[-97,-718],[230,472],[421,472],[927,-717]],np.float32) 

retval = cv2.getPerspectiveTransform(src, dst);
test = cv2.multiply(retval.copy(),retval.copy())

img1 = cv2.warpPerspective(img1,test,(640,480))

img2 = cv2.warpPerspective(img2,retval,(640,480))
img2 = cv2.warpPerspective(img2,retval,(640,480))

为什么img1和img2不一样? 如何组合透视变换矩阵?

由于

1 个答案:

答案 0 :(得分:0)

你误解了 cv2.multiply()的目的。它用于倍增图像并逐点进行乘法,如果 A = cv2.multiply( B C )那么 a i,j = b i,j * c i,j 对于所有我,j。

要进行正确的矩阵乘法,您需要使用功能强大但复杂的 cv2.gemm(),或者使用生成的转换为numpy数组并使用内置的事实dot()功能

import numpy as np  
import cv2

# test images
img1 = np.zeros((600,600,3),np.uint8)
img1[:] = (255,255,255)
cv2.fillConvexPoly( img1,np.array([(250,50),(350,50),(350,550),(250,550)],np.int32), (0,0,255) )
img2 = img1.copy()

# source and destination coordinates
src = np.array([[0,0],[0,480],[640,480],[640,0]],np.float32)
dst = np.array([[-97,-718],[230,472],[421,472],[927,-717]],np.float32) 
# transformation matrix
retval = cv2.getPerspectiveTransform(src, dst);

# test1 is wrong, test2 is the application of the transform twice
test1 = cv2.multiply(retval.copy(),retval.copy())
test2 = cv2.gemm(retval,retval,1,None,0) 
# test3 is using matrix-multiplication using numpy
test3 = retval.dot(retval)

img2 = cv2.warpPerspective(img1,test2,(640,480))
img3 = cv2.warpPerspective(img1,test3,(640,480))

img4 = cv2.warpPerspective(img1,retval,(640,480))
img4 = cv2.warpPerspective(img4,retval,(640,480))

cv2.imshow( "one application of doubled transform", img2 )
cv2.imshow( "one applications using numpy", img3 )
cv2.imshow( "two applications of single transform", img4 )
cv2.waitKey()

请注意cv2转换来自 left ,因此如果您要应用 A 然后 B ,则必须应用 B .dot( A )作为组合。