目录
cv2.projectPoints 投影
矩阵计算投影
cv2.projectPoints 投影
cv2.projectPoints() 是 OpenCV 中的一个函数,用于将三维空间中的点(3D points)投影到二维图像平面上。这在计算机视觉中经常用于相机标定、物体姿态估计、3D物体与2D图像之间的映射等场景。
函数原型:
cv2.projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs)
objectPoints:3D点的集合,通常是物体的真实世界坐标。
rvec:旋转向量,表示物体相对于相机的旋转。
tvec:平移向量,表示物体相对于相机的位置。
cameraMatrix:相机的内参矩阵,通常通过相机标定得到。
distCoeffs:相机的畸变系数,通常是由相机标定得到的。
import cv2
import numpy as np# 定义 3D 点(假设这些点在一个立方体的表面上)
object_points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, -1], [1, 0, -1], [1, 1, -1], [0, 1, -1]], dtype=np.float32)# 定义相机内参矩阵
camera_matrix = np.array([[1000, 0, 320], # fx, 0, cx[0, 1000, 240], # 0, fy, cy[0, 0, 1] # 0, 0, 1
], dtype=np.float32)# 定义畸变系数(假设无畸变)
dist_coeffs = np.zeros((5, 1), dtype=np.float32)# 定义相机外参(旋转向量和平移向量)
rvec = np.array([0, 0, 0], dtype=np.float32) # 无旋转
tvec = np.array([0, 0, -10], dtype=np.float32) # 相机在 Z 轴正方向 5 个单位处# 将 3D 点投影到 2D 图像平面
image_points, _ = cv2.projectPoints(object_points, rvec, tvec, camera_matrix, dist_coeffs)# 创建一个空白图像(用于可视化)
image = np.zeros((480, 640, 3), dtype=np.uint8)image_points=np.squeeze(image_points,axis=1)
print(image_points)
# 在图像上绘制投影点
for point in image_points:x, y = point.ravel()cv2.circle(image, (int(x), int(y)), 3, (0, 255, 0), -1) # 绘制绿色圆点# 显示图像
cv2.imshow("Projected Points", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
矩阵计算投影
内参,外参用的左乘
import numpy as np
import cv2# 定义相机内参矩阵 (3x3)
K = np.array([[1000, 0, 320], # fx, 0, cx[0, 1000, 240], # 0, fy, cy[0, 0, 1]]) # 0, 0, 1# 定义相机外参:旋转矩阵 (3x3) 和平移向量 (3x1)
R = np.eye(3) # 假设相机没有旋转
t = np.array([[0], [0], [-10]]) # 相机在Z轴负方向平移10个单位# 生成随机3D点云 (Nx3)
num_points = 100
# points_3d = np.random.rand(num_points, 3) * 10 # 生成100个3D点,范围在[0, 10)points_3d = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, -1], [1, 0, -1], [1, 1, -1], [0, 1, -1]], dtype=np.float32)# 将3D点云从世界坐标系转换到相机坐标系
points_3d_cam = R @ points_3d.T + t # 3xN
points_3d_cam = points_3d_cam.T # 转置为Nx3# 将3D点云投影到2D图像平面
points_2d_homogeneous = K @ points_3d_cam.T # 3xN
points_2d = points_2d_homogeneous[:2, :] / points_2d_homogeneous[2, :] # 归一化
points_2d = points_2d.T # 转置为Nx2# 创建空白图像
image_size = (640, 480) # 图像尺寸
image = np.zeros((image_size[1], image_size[0], 3), dtype=np.uint8)print(points_2d)
# 将2D点绘制到图像上
for point in points_2d:x, y = int(point[0]), int(point[1])if 0 <= x < image_size[0] and 0 <= y < image_size[1]: # 确保点在图像范围内cv2.circle(image, (x, y), 3, (0, 255, 0), -1) # 绘制绿色圆点# 显示图像
cv2.imshow("2D Projection of Point Cloud", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
总结,两种方法的结果是一样的。