【摄像头标定】使用opencv进行双目摄像头的标定及矫正(python)
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
import numpy as np
import cv2
import glob
# 准备对象点,如 (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
# 准备一个用于存储所有图片对象点和图像点的空列表
objpoints = [] # 3d 点
imgpoints_l = [] # 左图像的 2d 点
imgpoints_r = [] # 右图像的 2d 点
images_left = glob.glob('left/*.jpg') # 获取左图像文件列表
images_right = glob.glob('right/*.jpg') # 获取右图像文件列表
for img_left, img_right in zip(images_left, images_right):
img_l = cv2.imread(img_left)
img_r = cv2.imread(img_right)
gray_l = cv2.cvtColor(img_l, cv2.COLOR_BGR2GRAY)
gray_r = cv2.cvtColor(img_r, cv2.COLOR_BGR2GRAY)
# 寻找像素特征
ret_l, corners_l = cv2.findChessboardCorners(gray_l, (7,6), None)
ret_r, corners_r = cv2.findChessboardCorners(gray_r, (7,6), None)
# 如果找到足够的特征点,将它们添加到对应的列表中
if ret_l and ret_r:
objpoints.append(objp)
imgpoints_l.append(corners_l)
imgpoints_r.append(corners_r)
# 绘制特征点
cv2.drawChessboardCorners(img_l, (7,6), corners_l, ret_l)
cv2.drawChessboardCorners(img_r, (7,6), corners_r, ret_r)
# 展示图片
# cv2.imshow('img_l', img_l)
# cv2.imshow('img_r', img_r)
# cv2.waitKey(500)
cv2.destroyAllWindows()
# 标定双目摄像头
ret_l, cameraMatrix_l, distCoeffs_l, rvecs_l, tvecs_l = cv2.calibrateCamera(objpoints, imgpoints_l, gray_l.shape[::-1], None, None)
ret_r, cameraMatrix_r, distCoeffs_r, rvecs_r, tvecs_r = cv2.calibrateCamera(objpoints, imgpoints_r, gray_r.shape[::-1], None, None)
# 获取立体校正的参数
(roi_l, roi_r) = cv2.stereoCalibrate(objpoints, imgpoints_l, imgpoints_r, cameraMatrix_l, distCoeffs_l, cameraMatrix_r, distCoeffs_r, gray_l.shape[::-1][1:], None, None)
# 获取立体校正映射
map_lx, map_ly = cv2.initUndistortRectifyMap(cameraMatrix_l, distCoeffs_l, None, cameraMatrix_l, gray_l.shape[::-1], cv2.CV_16SC2)
map_rx, map_ry = cv2.initUndistortRectifyMap(cameraMatrix_r, distCoeffs_r, None, cameraMatrix_r, gray_r.shape[::-1], cv2.CV_16SC2)
# 立体校正
img_l_rect = cv2.remap(img_l, map_lx, map_ly,
评论已关闭