Python Opencv SolvePnP 返回错误的平移向量
我正在尝试在Blender 3D中使用单应性来校准并找到一个虚拟相机的位置和旋转。我选择Blender是因为在进入现实世界之前,我可以先检查我的结果,这样在实际操作中会更容易。
我在固定相机的视角下渲染了十张棋盘的照片,分别在不同的位置和角度。然后,我使用OpenCV的Python库,通过cv2.calibrateCamera
从这十张图片中检测到的棋盘角点来找到内参矩阵,接着用这个矩阵在cv2.solvePnP
中计算外参(位置和旋转)。
不过,虽然估算的参数和实际值很接近,但我觉得有些不对劲。我最初估算的位置是(-0.11205481,-0.0490256,8.13892491)
,而实际位置是(0,0,8.07105)
。看起来还不错吧?
但是,当我稍微移动和旋转相机并重新渲染图像时,估算的位置却变得更远了。估算值是(-0.15933154,0.13367286,9.34058867)
,而实际值是(-1.7918,-1.51073,9.76597)
。Z值还算接近,但X和Y的差距就大了。
我完全搞不懂这是怎么回事。如果有人能帮我理清这个问题,我将非常感激。以下是代码(基于OpenCV提供的Python2校准示例):
#imports left out
USAGE = '''
USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<image mask>]
'''
args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
args = dict(args)
try: img_mask = img_mask[0]
except: img_mask = '../cpp/0*.png'
img_names = glob(img_mask)
debug_dir = args.get('--debug')
square_size = float(args.get('--square_size', 1.0))
pattern_size = (5, 8)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_points = []
h, w = 0, 0
count = 0
for fn in img_names:
print 'processing %s...' % fn,
img = cv2.imread(fn, 0)
h, w = img.shape[:2]
found, corners = cv2.findChessboardCorners(img, pattern_size)
if found:
if count == 0:
#corners first is a list of the image points for just the first image.
#This is the image I know the object points for and use in solvePnP
corners_first = []
for val in corners:
corners_first.append(val[0])
np_corners_first = np.asarray(corners_first,np.float64)
count+=1
term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 )
cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
if debug_dir:
vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.drawChessboardCorners(vis, pattern_size, corners, found)
path, name, ext = splitfn(fn)
cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
if not found:
print 'chessboard not found'
continue
img_points.append(corners.reshape(-1, 2))
obj_points.append(pattern_points)
print 'ok'
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h))
print "RMS:", rms
print "camera matrix:\n", camera_matrix
print "distortion coefficients: ", dist_coefs.ravel()
cv2.destroyAllWindows()
np_xyz = np.array(xyz,np.float64).T #xyz list is from file. Not shown here for brevity
camera_matrix2 = np.asarray(camera_matrix,np.float64)
np_dist_coefs = np.asarray(dist_coefs[:,:],np.float64)
found,rvecs_new,tvecs_new = cv2.solvePnP(np_xyz, np_corners_first,camera_matrix2,np_dist_coefs)
np_rodrigues = np.asarray(rvecs_new[:,:],np.float64)
print np_rodrigues.shape
rot_matrix = cv2.Rodrigues(np_rodrigues)[0]
def rot_matrix_to_euler(R):
y_rot = asin(R[2][0])
x_rot = acos(R[2][2]/cos(y_rot))
z_rot = acos(R[0][0]/cos(y_rot))
y_rot_angle = y_rot *(180/pi)
x_rot_angle = x_rot *(180/pi)
z_rot_angle = z_rot *(180/pi)
return x_rot_angle,y_rot_angle,z_rot_angle
print "Euler_rotation = ",rot_matrix_to_euler(rot_matrix)
print "Translation_Matrix = ", tvecs_new
1 个回答
31
我想你可能把 tvecs_new
当成了相机的位置。其实这有点让人困惑,它并不是相机的位置!实际上,它是世界原点在相机坐标系中的位置。如果你想得到相机在物体或世界坐标系中的姿态,我认为你需要这样做:
-np.matrix(rotation_matrix).T * np.matrix(tvecs_new)
你可以通过 cv2.decomposeProjectionMatrix(P)[-1]
来获取欧拉角,其中 P
是 [r|t]
的 3x4 外部矩阵。
我发现 这篇文章对内参和外参的解释非常不错...