相机标定-python

代码chatGpt生成

 1 import numpy as np
 2 import cv2
 3 
 4 # 定义棋盘格大小和格子数
 5 CHESSBOARD_SIZE = (7, 6)
 6 CHESSBOARD_SQUARE_SIZE = 25
 7 
 8 # 设置标定图像文件夹路径以及输出的标定结果文件路径
 9 IMAGES_FOLDER_PATH = './calibration_images/'
10 CALIBRATION_FILE_PATH = './calibration.xml'
11 
12 # 准备物理坐标
13 object_points = np.zeros((CHESSBOARD_SIZE[0] * CHESSBOARD_SIZE[1], 3), np.float32)
14 object_points[:, :2] = np.mgrid[0:CHESSBOARD_SIZE[0], 0:CHESSBOARD_SIZE[1]].T.reshape(-1, 2)
15 object_points *= CHESSBOARD_SQUARE_SIZE
16 
17 # 准备图像数据
18 image_paths = [IMAGES_FOLDER_PATH + f for f in os.listdir(IMAGES_FOLDER_PATH)]
19 image_size = None
20 image_points = []
21 object_points_list = []
22 for image_path in image_paths:
23     image = cv2.imread(image_path)
24     gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
25     ret, corners = cv2.findChessboardCorners(gray_image, CHESSBOARD_SIZE, None)
26     if ret:
27         # 找到了棋盘格角点,保存图像和物理坐标
28         image_points.append(corners.reshape(-1, 2))
29         object_points_list.append(object_points)
30         if image_size is None:
31             image_size = gray_image.shape[::-1]
32 
33 # 执行相机标定
34 ret, camera_matrix, distortion_coefficients, r_vector_list, t_vector_list = cv2.calibrateCamera(
35     object_points_list, image_points, image_size, None, None)
36 
37 # 输出结果
38 print('camera_matrix:')
39 print(camera_matrix)
40 print('distortion_coefficients:')
41 print(distortion_coefficients)
42 print('r_vectors:')
43 print(r_vector_list)
44 print('t_vectors:')
45 print(t_vector_list)
46 
47 # 保存标定结果
48 fs = cv2.FileStorage(CALIBRATION_FILE_PATH, cv2.FILE_STORAGE_WRITE)
49 fs.write('camera_matrix', camera_matrix)
50 fs.write('distortion_coefficients', distortion_coefficients)
51 fs.release()
View Code

 

posted @ 2023-03-23 14:50  路人加  阅读(31)  评论(0编辑  收藏  举报