распиши мне подробно код получения карты глубин с помощью opencv на python. Код должен включать чтение фотографий с левой и правой камеры, калибровку камер, удаление искажений при помощи функции remap получение карты глубин изображения и преобразование карты глубин в облако точек и координатами x, y, z
Assistant
Чтобы получить карту глубины с помощью OpenCV на Python, нужно выполнить несколько шагов, включая чтение из камер, калибровку камеры, коррекцию искажений и преобразование во вложенные списки, где каждый список содержит координаты x, y и глубины z. Ниже приведен примерный код, который демонстрирует этот процесс.
Предположим, что у вас есть четыре изображения для каждой камеры, которые представляют границы камеры (например, квадраты на фоне):
left_frame.jpg - изображение с левой камеры
right_frame.jpg - изображение с правой камеры
camera_matrix.jpg - изображение для калибровки, отображающее точку на экран камеры и соответствующую точку в мировом пространстве
dist_coeffs.jpg - изображение с коэффициентами искажений, требуемыми для калькуляции калькулятора
python
import cv2
import numpy as np
def read_frames(left_frame_path, right_frame_path):
left_frame = cv2.imread(left_frame_path, cv2.IMREAD_GRAYSCALE)
right_frame = cv2.imread(right_frame_path, cv2.IMREAD_GRAYSCALE)
return left_frame, right_frame
def calibrate(left_frame, right_frame, chessboard_size=(9, 6)):
# Предполагаем, что ключевые точки имеют форму 9x6 сетки
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
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)
objpoints = [] # List of calibration points in 3D
imgpoints_left = [] # List of image points from left camera
imgpoints_right = [] # List of image points from right camera
gray_left = cv2.cvtColor(left_frame, cv2.COLOR_BGR2GRAY)
gray_right = cv2.cvtColor(right_frame, cv2.COLOR_BGR2GRAY)
ret_left, corners_left = cv2.findChessboardCorners(gray_left, chessboard_size, None)
ret_right, corners_right = cv2.findChessboardCorners(gray_right, chessboard_size, None)
if ret_left and ret_right:
objpoints.append(objp)
cv2.cornerSubPix(gray_left, corners_left, (11, 11), (-1, -1), criteria)
imgpoints_left.append(corners_left)
cv2.cornerSubPix(gray_right, corners_right, (11, 11), (-1, -1), criteria)
imgpoints_right.append(corners_right)
return objpoints, imgpoints_left, imgpoints_right
def calibrate_camera(objpoints, imgpoints_left, imgpoints_right):
ret, mtx_left, dist_left, rvecs_left, tvecs_left = cv2.calibrateCamera(objpoints, imgpoints_left, left_frame.shape[::-1], None, None)
ret, mtx_right, dist_right, rvecs_right, tvecs_right = cv2.calibrateCamera(objpoints, imgpoints_right, right_frame.shape[::-1], None, None)
return mtx_left, dist_left, rvecs_left, tvecs_left, mtx_right, dist_right, rvecs_right, tvecs_right
def undistort_image(image, mtx, dist):
h, w = image.shape[:2]
new_camera_mtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
# Undistort
undistorted_image = cv2.undistort(image, mtx, dist, None, new_camera_mtx)
# Crop the image
x, y, w, h = roi
undistorted_image = undistorted_image[y:y+h, x:x+w]
return undistorted_image
def remap(image, mtx, dist):
h, w = image.shape[:2]
map1, map2 = cv2.initUndistortRectifyMap(mtx, dist, None, None, (w, h), 5)
remap_image = cv2.remap(image, map1, map2, cv2.INTER_LINEAR)
return remap_image
def calculate_depth_map(left_frame_path, right_frame_path, camera_matrix_path, dist_coeffs_path, chessboard_size=(9, 6)):
left_frame, right_frame = read_frames(left_frame_path, right_frame_path)
objpoints, imgpoints_left, imgpoints_right = calibrate(left_frame, right_frame, chessboard_size)
mtx_left, dist_left, _, _, mtx_right, dist_right, _, _ = calibrate_camera(objpoints, imgpoints_left, imgpoints_right)
left_undistorted = undistort_image(left_frame, mtx_left, dist_left)
right_undistorted = undistort_image(right_frame, mtx_right, dist_right)
left_remap = remap(left_undistorted, mtx_left, dist_left)
right_remap = remap(right_undistorted, mtx_right, dist_right)
# Calculate disparity map
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(left_remap, right_remap)
# Convert disparity to depth map
# Assuming known focal length and baseline (distance between cameras)
focal_length = 700 # Placeholder value
baseline = 0.1 # Placeholder value
depth_map = (focal_length * baseline) / (disparity + 1e-5)
# Convert depth map to 3D points
points_3d = []
for i in range(depth_map.shape[0]):
for j in range(depth_map.shape[1]):
if depth_map[i, j] > 0: # Ignore invalid depth values
Z = (focal_length * baseline)