Python 利用棋盘格进行相机标定,求出物体的相机坐标系 代码
时间: 2024-02-16 10:31:23 浏览: 88
Python opencv相机标定实现原理及步骤详解
5星 · 资源好评率100%
以下是 Python 中使用棋盘格进行相机标定并求出物体的相机坐标系的示例代码:
```python
import numpy as np
import cv2
# 棋盘格规格
chessboard_size = (9, 6)
# 准备棋盘格图像点
objp = np.zeros((chessboard_size[0] * chessboard_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:chessboard_size[0], 0:chessboard_size[1]].T.reshape(-1, 2)
# 存储棋盘格图像点和世界坐标系点的数组
obj_points = []
img_points = []
# 加载图像
img = cv2.imread('chessboard.png')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 寻找棋盘格角点
ret, corners = cv2.findChessboardCorners(gray, chessboard_size, None)
# 如果找到角点,添加到数组中
if ret == True:
obj_points.append(objp)
img_points.append(corners)
# 绘制棋盘格角点
cv2.drawChessboardCorners(img, chessboard_size, corners, ret)
# 进行相机标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray.shape[::-1], None, None)
# 计算物体的相机坐标系
img_points = np.array(img_points)
rvecs = np.array(rvecs)
tvecs = np.array(tvecs)
obj_points = np.array(obj_points)
R, _ = cv2.Rodrigues(rvecs[0])
T = tvecs[0]
P = np.dot(mtx, np.hstack((R, T)))
P_inv = np.linalg.inv(P)
obj_points_homog = np.hstack((obj_points, np.ones((obj_points.shape[0], 1))))
img_points_homog = np.hstack((img_points, np.ones((img_points.shape[0], 1))))
world_points_homog = np.dot(P_inv, img_points_homog.T).T
world_points = np.zeros((world_points_homog.shape[0], 3))
world_points[:, 0] = world_points_homog[:, 0] / world_points_homog[:, 3]
world_points[:, 1] = world_points_homog[:, 1] / world_points_homog[:, 3]
world_points[:, 2] = world_points_homog[:, 2] / world_points_homog[:, 3]
print("物体的相机坐标系:")
print(world_points)
# 显示图像
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("没有找到棋盘格角点")
```
需要注意的是,棋盘格图像应该是正面视图,而且每个棋盘格都必须要完全可见。另外,这是一个简单的示例代码,实际情况中需要更多的处理和优化。
阅读全文