python - 如何使用 `cv2.perspectiveTransform` 在 Python OpenCV 中的一组点上应用单应性?

标签 python numpy opencv homography

我想将单应性应用于以下几点:

array([[-7.4894,  1.8873],
   [-7.4973,  1.8543],
   [-7.5375,  1.6725],
   [-7.5681,  1.522 ],
   [-7.5961,  1.371 ],
   [-7.6252,  1.2013],
   [-7.6504,  1.031 ],
   [-7.667 ,  0.8985],
   [-7.6817,  0.7657],
   [-7.6954,  0.613 ],
   [-7.7054,  0.4786],
   [-7.7124,  0.3452],
   [-7.7182,  0.1931],
   [-7.7215,  0.0866],
   [-7.7716,  0.0872],
   [-7.7715,  0.0929],
   [-7.7651,  0.2884],
   [-7.7587,  0.4269],
   [-7.7528,  0.5233],
   [-7.7418,  0.6616],
   [-7.7275,  0.8116],
   [-7.7048,  1.0032],
   [-7.6916,  1.0988],
   [-7.6686,  1.2478],
   [-7.6352,  1.4379],
   [-7.6091,  1.5741],
   [-7.5784,  1.7219],
   [-7.538 ,  1.8995],
   [-7.4894,  1.8873]], dtype=float32)

我的相机单应矩阵是这样的:

array([[ 3.9643041e-04,  6.5913662e-07,  3.1965813e-03],
       [ 7.4297395e-07, -3.9652368e-04, -4.4492882e-04],
       [-9.3076696e-06, -3.5773560e-06,  1.0000000e+00]], dtype=float32)

当我尝试使用 cv2.perspectiveTransform 应用单应性时,出现以下错误:

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

我怀疑每个点都需要另一个维度。但我不确定如何使用 numpy 添加此维度。

解决这个问题的正确方法是什么?有没有办法确定根本原因?错误消息对我来说意义不大。

最佳答案

确保点的形状是(n, 1, 2)(1,n,2):

 pts = np.float32(pts).reshape(-1,1,2)
 #pts = np.array([pts], np.float32)
 cv2.perspectiveTransform(pts, M)

例如:

pts = np.array([[1,2,],[3,4]], np.float32)
M = np.array([[ 3.9643041e-04,  6.5913662e-07,  3.1965813e-03],
              [ 7.4297395e-07, -3.9652368e-04, -4.4492882e-04],
              [-9.3076696e-06, -3.5773560e-06,  1.0000000e+00]], dtype=np.float32)

## (n, 1, 2)
pts1 = pts.reshape(-1,1,2).astype(np.float32)
dst1 = cv2.perspectiveTransform(pts1, M)

## (1, n, 2)
pts2 = np.array([pts], np.float32)
dst2 = cv2.perspectiveTransform(pts2, M)

结果:

>>> print(pts1)
[[[1. 2.]]

 [[3. 4.]]]
>>> print(dst1)
[[[ 0.00359439 -0.00123725]]

 [[ 0.00438869 -0.00202888]]]
>>> print(pts2)
[[[1. 2.]
  [3. 4.]]]
>>> print(dst2)
[[[ 0.00359439 -0.00123725]
  [ 0.00438869 -0.00202888]]]

还有一个例子:

How do I use the relationships between Flann matches to determine a sensible homography?

关于python - 如何使用 `cv2.perspectiveTransform` 在 Python OpenCV 中的一组点上应用单应性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55055655/

相关文章:

python - 使用图像的局部平均颜色来减少闪电差异

python - WebSocket握手时出错: Unexpected response code: 200 with ChromeDriver and Selenium

python - 错误号 111 : Connection refused when connecting to Elasticsearch with Python Script

python:从外部代码导入 numpy 作为 np 在我自己的用户定义模块中丢失

python - 计算第一行第一列输入的数组值

python - Numpy 中的一维 LDA 输出维度

python - 使用 xyz 数据框在 Python 中生成热图

适合初学者的 Python 套接字/中断

python - 将时刻与阈值图像一起使用时出现 OpenCV TypeError

c++ - Mat::checkVector 在 OpenCV 中做了什么?