如何从世界坐标转换为像素坐标?代码结果超限问题排查
世界坐标转像素坐标结果超出范围问题排查
问题场景
我需要将已知世界坐标转换为目标物体的像素坐标,但运行代码后得到的像素坐标值超出了1920×1080的图像分辨率范围,使用标准相机投影矩阵计算,代码如下:
import numpy as np focal_length = 1386 f_x = focal_length f_y = focal_length c_x = 1920/2 c_y = 1080/2 # 计算像素坐标 m_Rotation= np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # 单位旋转矩阵 print("\n m_Rotation \n", m_Rotation) m_Translation = np.array([[8, 1, 5]]) print("\n m_Translation \n", m_Translation) m_Transformation = np.concatenate((m_Rotation, m_Translation.T), axis=1) print("\n m_Transformation \n", m_Transformation) m_target = np.array([[5], [10], [2], [1]]) # 世界齐次坐标 print("\n m_target \n", m_target) result1 = np.dot(m_Transformation, m_target) print("\n result1 \n", result1) m_intrinsic = np.array([[f_x, 0, c_x], [0, f_y, c_y], [0, 0, 1]]) print("\n m_intrinsic \n", m_intrinsic) result2 = np.dot(m_intrinsic, result1) print("\n result2 \n", result2/result2[2])
问题根源
- 外参矩阵平移方向错误:
标准相机外参矩阵[R | t]中,t是世界原点在相机坐标系下的平移向量,等价于相机在世界坐标系下的位置C = -R.T @ t。当前设置的m_Translation = [8,1,5]是相机的世界位置,而非世界原点到相机的平移向量,导致外参构造逻辑错误。 - 目标点位于相机后方:
即使忽略平移错误,相机世界位置为[8,1,5],目标点为[5,10,2],因旋转矩阵是单位矩阵,相机坐标系与世界坐标系完全一致,目标点在相机坐标系下的z坐标为2-5=-3,处于相机光轴反方向(后方),相机无法捕捉该点,投影结果必然无效。
解决方法
1. 修正外参矩阵构造
将平移向量改为世界原点在相机坐标系下的向量,即t = -R @ C(C为相机世界位置)。因旋转矩阵是单位矩阵,直接取t = [-8,-1,-5]即可。
2. 确保目标点在相机前方
调整相机或目标点位置,使相机坐标系下的目标点z坐标为正(光轴正方向)。例如让相机位于世界原点,目标点在光轴正方向的远处,保证投影后的像素落在分辨率范围内。
修正后代码示例
import numpy as np focal_length = 1386 f_x = focal_length f_y = focal_length c_x = 1920/2 c_y = 1080/2 # 相机位于世界原点,外参矩阵为单位矩阵 m_Rotation= np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) m_Translation = np.array([[0, 0, 0]]) m_Transformation = np.concatenate((m_Rotation, m_Translation.T), axis=1) # 目标点在相机前方10米处,世界坐标[1,1,10] m_target = np.array([[1], [1], [10], [1]]) result1 = np.dot(m_Transformation, m_target) m_intrinsic = np.array([[f_x, 0, c_x], [0, f_y, c_y], [0, 0, 1]]) result2 = np.dot(m_intrinsic, result1) pixel_coords = result2/result2[2] print("\n 修正后的像素坐标:\n", pixel_coords)
运行后输出像素坐标为[[1098.6], [678.6]],完全处于1920×1080的分辨率范围内。
内容的提问来源于stack exchange,提问作者HusCet
相关产品推荐
相关产品推荐

