Python Opencv SolvePnP 产生错误的平移向量。

17

我正在尝试使用单个虚拟摄像机在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 calibrate示例):

#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

我有同样的问题,不过我正在使用不同的方法。希望这里有人知道答案。https://dev59.com/KmYq5IYBdhLWcg3wfgrd - b_m
嗯,b_m,看起来我们处于同一艘船上哈哈。希望有人能帮助我们。我如何直接从Rodrigues获得欧拉角?对我而言,3x1旋转向量与欧拉角不同。另外,我的solvePnP输入是否正确?这是您如何使用calibratecamera的输出吗? - amartin7211
@user1713402 抱歉我完全搞混了,你是对的,solvePnP返回的3x1不是欧拉角,抱歉。我的建议是你找一个具体的例子,看看solvePnP为什么会给出意外的结果。列出输入的三维和二维坐标以及相机矩阵,以及你认为solvePnP输出错误的原因。 - Hammer
1
是的,请发布您的数据 :) - fraxel
有人能告诉我什么是xyz吗?它不是指obj点吗? - touchStone
显示剩余2条评论
1个回答

31

我认为你可能将tvecs_new视为相机位置。有点令人困惑,但实际上它是相机坐标系下的世界原点位置。如果想获取对象/世界坐标系下的相机姿态,我相信你需要:

-np.matrix(rotation_matrix).T * np.matrix(tvecs_new)

你可以使用cv2.decomposeProjectionMatrix(P)[-1]获得欧拉角,其中P[r|t] 3x4外参矩阵。

我发现这篇文章对内参和外参有很好的介绍...


1
哇!运行得非常好!非常感谢。我还没有看到这篇文章(我打算看),但这确实修复了结果。我有点困惑你所说的“它是相机坐标系中世界原点的位置”的意思。您能简要解释一下吗?相机坐标系是什么?此外,使用分解获得的欧拉角与我的计算欧拉角相对应(尽管我将坚持使用OpenCV的代码)。 - amartin7211
1
@user1713402 - 很酷 :)。“相机坐标系”是相机的笛卡尔坐标系,它随着相机移动,而相机始终位于原点,z轴是相机视图的方向,y是图像的上方,x是向右的方向。而世界坐标系是静态的,相机在其中移动。这里有另一个问题更详细地解释了它。 - fraxel
太好了!那很有道理!再次感谢。 - amartin7211
这个很好用,但是x和y轴的欧拉值不适合Blender坐标系统。 - Eyshika

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接