Python中OpenCV cv2.solvePnP返回结果偏差过大问题求助
cv2.solvePnP返回结果与预期偏差极大
使用Python版OpenCV的cv2.solvePnP函数时,发现返回的旋转矩阵和平移向量与生成数据时使用的变换矩阵偏差极大。尝试调整函数参数未解决问题,多数情况下还会报错。
环境信息:
- Python 3.11.5
- opencv-python 4.9.0.80
- numpy 1.26.4
测试代码如下:
import numpy as np import cv2 k = np.eye(3) # I added this here for the code to run. I use some matrix from a file. it is not suppose to change the results, since we use the same matrix for the creating the data and for cv2.solvePnP # create 3d points in homogenous coordinates points_3d = np.array([ [1.0, 1.0, 8.0, 1.0], [1.0, -1.0, 7.9, 1.0], [-1.0, 1.0, 8.0, 1.0], [-1.0, -1.0, 9.0, 1.0], ]).T # create trivial transformation that rotate by pi/8 around the Z axis(the camera line of sight) transformation = np.array([ [np.cos(np.pi/8), -np.sin(np.pi/8), 0.0, 0.0], [np.sin(np.pi/8), np.cos(np.pi/8), 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], ]) # project the 3D points to the camera as pixels pixels_2d = k @ transformation @ points_3d pixels_2d /= pixels_2d[2, :] pixels_2d = pixels_2d[:2, :] # fix the format of the array according to OpenCV docs pixels_2d = np.ascontiguousarray(pixels_2d.reshape((4, 1, 2))) points_3d = np.ascontiguousarray(points_3d[:3, :].reshape((4, 3))) # call cv2.solvePnP _, r, t = cv2.solvePnP(points_3d, pixels_2d, k, None, flags=cv2.SOLVEPNP_P3P) # The expected results suppose to be very close to the rotation and translating that create the data. r, _ = cv2.Rodrigues(r) print(f'rotation matrix R=\n{r}\ntranslation vector t=\n{t}')
实际输出:
rotation matrix R= [[ 0.33196511 -0.65448479 -0.67930025] [ 0.73226038 0.63276397 -0.25180249] [ 0.59463762 -0.41383501 0.68930884]] translation vector t= [[-0.10543042] [ 1.17869639] [ 4.22398241]]
预期返回的旋转矩阵和平移向量应与生成数据时使用的变换矩阵(绕Z轴旋转π/8的矩阵)接近,但实际输出偏差明显。
内容的提问来源于stack exchange,提问作者Reuven Mol
相关产品推荐
相关产品推荐

