错误:(-215:断言失败)函数“cv::perspectiveTransform”中的 scn + 1 == m.cols

问题描述 投票:0回答:4

下面是一个Python脚本,它计算两个图像之间的单应性,然后将所需的点从一个图像映射到另一个图像

import cv2

import numpy as np


if __name__ == '__main__' :

  # Read source image.
  im_src = cv2.imread(r'C:/Users/kjbaili/.spyder-py3/webcam_calib/homography/khaledd 35.0 sec.jpg')

  # Five corners of the book in source image
  pts_src = np.array([[281, 238], [325, 297], [283, 330],[248, 325],[213, 321]])

  # Read destination image.
  im_dst = cv2.imread(r'C:/Users/kjbaili/.spyder-py3/webcam_calib/homography/20.jpg')

  # Five corners of the book in destination image.
  pts_dst = np.array([[377, 251],[377, 322],[316, 315],[289, 284],[263,255]])



  # Calculate Homography

  h, status = cv2.findHomography(pts_src, pts_dst)


  
  # provide a point i wish to map from image 1 to image 2
  a = np.array([[260, 228]])


  

  pointsOut = cv2.getPerspectiveTransform(a, h)

  # Display image
  cv2.imshow("treced_point_image", pointsOut)


  cv2.waitKey(0)
cv2.destroyAllWindows()

但是,当我显示包含映射点的图像时,它会返回以下错误:

error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\core\src\matmul.dispatch.cpp:531: 
error: (-215:Assertion failed) scn + 1 == m.cols in function 'cv::perspectiveTransform'

据我所知,此错误意味着分配给函数透视变换的参数不正确或未被读取。我在阅读步骤中检查了这两个图像,一切都很好。 所以有人知道为什么会发生这种情况吗?

提前致谢 哈立德

python numpy opencv computer-vision homography
4个回答
3
投票

我认为您的代码中有两个错误。首先,你应该使用 cv2.getPerspectiveTransform() 获取变换矩阵。其次,要做到 实际的点变换,需要调用cv2.perspectiveTransform()。 cv2.perspectiveTransform() 期望 3 或 4 维矩阵作为输入。那么你 需要提供类似于以下内容的内容。注意 3 维数组 下面代码中的“pts”。我在“pts”数组中只有一个点。您可以添加更多。

import cv2    
import numpy as np

# determine the transform matrix
src = np.float32([[0, 1280], [1920, 1280], [1920, 0], [0, 0]])    
dst = np.float32([[0, 600], [400, 600], [400, 0], [0, 0]])    
perspective_transform = cv2.getPerspectiveTransform(src, dst)    

# use the above matrix to transform required pixels
pts = np.float32(np.array([[[1920, 1280]]]))    
warped_pt = cv2.perspectiveTransform(pts, perspective_transform)[0]    
print ("warped_pt = ", warped_pt)

2
投票

您向

cv2.getPerspectiveTransform()
传递了错误的参数。该函数需要原始图像中的一组四个坐标和转换图像中的新坐标。您可以直接将
pts_src
pts_dst
传递给函数,您将得到变换矩阵。然后你可以通过矩阵乘法得到点“a”的变换坐标,如
a_transformed = np.dot(matrix, a)


0
投票

我实际上发现函数 cv2.findHomography() 已经通过查找两个平面之间的透视变换来完成工作,因此我不再需要 cv2.perspectiveTransform()。


0
投票

注意:代码片段是Python语言的。 求变换矩阵: 所以原则上,你可以使用以下任意一种方法来计算变换矩阵。

i) cv2.findHomography() 或 ii) cv2.getPerspectiveTransform()

小的区别是,当您提供 4 组您有信心的手动点时,您可以使用 cv2.getPerspectiveTransform(),但是当您有 50 个点并且想要使用 RANSAC 等技术过滤点时,请使用 cv2.findHomography() .

使用变换矩阵变换点:

您可以使用变换矩阵来变换点,有两个选项: i) 使用perspectiveTransform() 变换点集。您可能需要确保数据类型需要是 float64 numpy 数组(使用 pts = np.array(pts,np.float64)),结果形状为 (n,1,2) (pts = pts.reshape((- 1, 1, 2))).

ii)(从接受的答案中获得)使用“np.dot(transformation_matrix,a)”变换单个点。其中“a”是 XY 坐标。

© www.soinside.com 2019 - 2024. All rights reserved.