使用 OpenCV 3.3 在 Python 2.7 中使用 triangulatePoints 每次输出 3D 点都会发生变化

Output 3D points change everytime in triangulatePoints using in Python 2.7 with OpenCV 3.3

我想使用 Python 2.7 和 OpenCV 3.3 中的 triangulatePoints 了解立体相机的 3D 点。为此,我校准了立体相机并将矩阵存储在文件夹中。我还使用 cv2.stereoRectify 校正了我的图像,并使用 cv2.initUndistortRectifyMap 消除了图像失真。然后我保存了这些图像以及投影矩阵 P1 和 P2 并在两个图像中找到对应点。左图中的点 ptl = np.array([304,277]) 和右图中的对应点 ptr = np.array([255,277])。之后我尝试了 points = cv2.triangulatePoints(P1,P2,ptl,ptr)。代码是:

    import cv2
        import numpy as np
        import matplotlib.pyplot as plt

        cameraMatrixL = np.load('mtx_left.npy')
        distCoeffsL = np.load('dist_left.npy')
        cameraMatrixR = np.load('mtx_right.npy')
        distCoeffsR = np.load('dist_right.npy')
        R = np.load('R.npy')
        T = np.load('T.npy')
    # following matrices I saved which i got from stereoRectify
        R1 = np.load('R1.npy')
        R2 = np.load('R2.npy')
        P1 = np.load('P1.npy')
        P2 = np.load('P2.npy')
        Q = np.load('Q.npy')
# upload alreday distorted and rectified images
        imgL = cv2.imread('D:\python/triangulate in 3 D\left.png',0)
        imgR = cv2.imread('D:\python/triangulate in 3 D/right.png',0)
        ptl = np.array([304,277]) # point in left image
        ptr = np.array([255,277]) # Corresponding point in right image
        points = cv2.triangulatePoints(P1,P2,ptl,ptr)
        print points

但是每当我 运行 这段代码时,我的结果都发生了变化(而且所有结果都是错误的)。一次结果看起来像

[[  518845863]
 [ 1667138857]
 [-1189385102]
 [    -661713]]

另一次结果看起来像

[[-1766436066]
 [          0]
 [          0]
 [-1299735447]]

有时看起来像

[[        0]
 [        0]
 [697559541]
 [        0]]

我不知道为什么即使我的所有参数都相同,结果也会发生变化?此外,这些 3D 点不正确。如何纠正这些问题?

编辑: 我在这段代码中观察到一件事,在 运行ning 之后它没有完成。它既不显示 Process finished with exit code 0 也不显示 Process finished with exit code 1。当我按下红色停止按钮时,它以 Process finished with exit code 1 结束。为什么这样?我认为由于这个原因,只会出现上述错误。为什么这个代码不是 运行 Process finished with exit code 0?

终于,经过这么多次尝试,我发现了我做错了什么。实际上,我在代码中以错误的方式定义了我的观点。根据triangulatePoints document,积分应该是

projPoints1 – 2xN array of feature points in the first image.

但是在我写的代码中

ptl = np.array([304,277]) # point in left image
ptr = np.array([255,277]) # Corresponding point in right image

意味着我正在定义 1x2 数组,而我应该为单点定义 2x1 数组。同样对于 5 点数组应该是 2x5N 点偏离航线 2xN。最初,我没有注意到这一点,因为我曾经在 Matlab 中进行训练,并且相应的点被用作 Nx2 array.Now 我把我的点放在

l = np.array([[ 304],[ 277]],dtype=np.float)
r = np.array([[ 255 ],[ 277]],dtype=np.float)

我让上面的代码工作了。

还有一个点dtype=np.float很重要,定义这个点数组可以避免错误的结果。

我得到的结果不是很准确,显示误差将近 20-25 毫米,但我解决了上述问题,所以我回答了这个问题,现在我必须找出减少误差的方法。如果有人知道如何减少错误请告诉我。