python实现双目相机标定代码
时间: 2023-07-23 22:08:18 浏览: 177
双目相机标定代码
以下是Python实现的双目相机标定代码,使用OpenCV库:
```python
import numpy as np
import cv2
# 棋盘格尺寸,单位为毫米
square_size = 20
# 棋盘格角点数量
pattern_size = (9, 6)
# 标定板角点的三维坐标
objp = np.zeros((np.prod(pattern_size), 3), dtype=np.float32)
objp[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2) * square_size
# 存储棋盘格角点的世界坐标和图像坐标
obj_points = []
img_points_left = []
img_points_right = []
# 读取图像
images_left = sorted(glob.glob("left*.jpg"))
images_right = sorted(glob.glob("right*.jpg"))
# 查找棋盘格角点
for i, fname in enumerate(images_left):
# 读取图像
img_left = cv2.imread(fname)
img_right = cv2.imread(images_right[i])
# 转换为灰度图像
gray_left = cv2.cvtColor(img_left, cv2.COLOR_BGR2GRAY)
gray_right = cv2.cvtColor(img_right, cv2.COLOR_BGR2GRAY)
# 查找棋盘格角点
ret_left, corners_left = cv2.findChessboardCorners(gray_left, pattern_size, None)
ret_right, corners_right = cv2.findChessboardCorners(gray_right, pattern_size, None)
if ret_left and ret_right:
# 亚像素精度优化
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
cv2.cornerSubPix(gray_left, corners_left, (5, 5), (-1, -1), criteria)
cv2.cornerSubPix(gray_right, corners_right, (5, 5), (-1, -1), criteria)
# 添加到对象点数组和图像点数组中
obj_points.append(objp)
img_points_left.append(corners_left)
img_points_right.append(corners_right)
# 双目标定
ret, mtx_left, dist_left, mtx_right, dist_right, R, T, E, F = cv2.stereoCalibrate(
obj_points, img_points_left, img_points_right,
None, None, None, None,
img_left.shape[::-1], cv2.CALIB_FIX_INTRINSIC)
# 双目矫正
R1, R2, P1, P2, Q, roi_left, roi_right = cv2.stereoRectify(
mtx_left, dist_left, mtx_right, dist_right,
img_left.shape[::-1], R, T, None, None, None, None, None,
cv2.CALIB_ZERO_DISPARITY, 0)
# 生成立体映射
left_map1, left_map2 = cv2.initUndistortRectifyMap(mtx_left, dist_left, R1, P1, img_left.shape[::-1], cv2.CV_32FC1)
right_map1, right_map2 = cv2.initUndistortRectifyMap(mtx_right, dist_right, R2, P2, img_right.shape[::-1], cv2.CV_32FC1)
```
其中,`images_left`和`images_right`分别为左右相机拍摄的图像路径数组。可以使用`cv2.imread()`读取图像,并使用`cv2.cvtColor()`将图像转换为灰度图像。使用`cv2.findChessboardCorners()`查找棋盘格角点,如果找到了则将世界坐标和图像坐标存储到`obj_points`、`img_points_left`和`img_points_right`数组中。最后,使用`cv2.stereoCalibrate()`进行双目标定,使用`cv2.stereoRectify()`进行双目矫正,使用`cv2.initUndistortRectifyMap()`生成立体映射。
阅读全文