objpoints = [] # 3D points in real-world space
imgpoints = [] # 2D points in image plane
cap_thread = CaptureThread(device_id=device_id, resolution=(W, H))
buffer_manager = MultiBufferManager()
buffer_manager.bind_thread(cap_thread, buffer_size=8)
if cap_thread.connect_camera():
cap_thread.start()
else:
print(f"Cannot open device {device_id}")
return
i = -1
start_time = time.time()
while True:
i += 1
img = buffer_manager.get_device(device_id).get().image
if i % framestep != 0:
continue
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
found, corners = cv2.findChessboardCorners(gray, grid_size_tuple,
cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_NORMALIZE_IMAGE + cv2.CALIB_CB_FILTER_QUADS)
if found:
term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.01)
cv2.cornerSubPix(gray, corners, (5, 5), (-1, -1), term)
imgpoints.append(corners)
objpoints.append(grid_points)
cv2.drawChessboardCorners(img, grid_size_tuple, corners, found)
# 每秒刷新一次,显示当前检测到的角点数量
elapsed_time = time.time() - start_time
if elapsed_time >= 1:
corners_count = len(imgpoints)
start_time = time.time()
else:
corners_count = len(imgpoints)
# 显示检测到的角点数量
cv2.putText(img, f"Corners Detected: {corners_count}", (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 200, 0), 2)
cv2.imshow(f"Camera {device_id}", img)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
if len(objpoints) >= 12: # Check if enough corners were found
K = np.zeros((3, 3))
D = np.zeros((4, 1))
rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for _ in range(len(objpoints))]
tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for _ in range(len(objpoints))]
calibration_flags = (cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC +
cv2.fisheye.CALIB_CHECK_COND +
cv2.fisheye.CALIB_FIX_SKEW) if fisheye else 0
ret, mtx, dist, rvecs, tvecs = cv2.fisheye.calibrate(objpoints, imgpoints, (W, H), K, D, rvecs, tvecs, calibration_flags)
if ret:
fs = cv2.FileStorage(output_file, cv2.FILE_STORAGE_WRITE)
fs.write("resolution", np.int32([W, H]))
fs.write("camera_matrix", K)
fs.write("dist_coeffs", D)
fs.release()
print(f"Camera {device_id} calibrated successfully and saved to {output_file}")
else:
print(f"Camera {device_id} calibration failed")
else:
print(f"Not enough corners found for camera {device_id}")
cap_thread.stop()
cap_thread.disconnect_camera()
cv2.destroyAllWindows()
def main():
cameras = [
(0, './yaml/front.yaml'),
(2, './yaml/fback.yaml'),
(4, './yaml/left.yaml'),
(6, './yaml/right.yaml'),
]
In this case, when you run this script directly, it will execute the main() function. However, if you import this script as a module in another script, the main() function won't be called automatically.