一、利用深度相机实时测距
代码一(实时显示窗口中心点处的距离信息):
# distance_center
import pyrealsense2 as rs
import numpy as np
import cv2
# 初始化深度相机
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
pipeline.start(config)
try:
while True:
try:
# 等待深度数据帧和RGB数据帧,设置等待时间为10秒
frames = pipeline.wait_for_frames(timeout_ms=10000)
depth_frame = frames.get_depth_frame()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
continue
# 获取深度图像的原始数据
depth_data = np.asanyarray(depth_frame.get_data())
# 获取RGB图像的原始数据
color_data = np.asanyarray(color_frame.get_data())
# 在深度图像上叠加距离信息
depth_value = depth_frame.get_distance(320, 240) # 320, 240是图像中心像素坐标
distance_in_meters = round(depth_value, 2)
cv2.putText(color_data, f"Distance: {distance_in_meters} m", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# 在图像中心上点上加上标记
center_x, center_y = 320, 240 # 图像中心像素坐标
cv2.drawMarker(color_data, (center_x, center_y), (0, 255, 0), cv2.MARKER_CROSS, markerSize=20, thickness=2)
# 使用伪彩色映射器将深度数据转换为伪彩色图像
colorizer = rs.colorizer()
depth_colormap = np.asanyarray(colorizer.colorize(depth_frame).get_data())
# 创建一个窗口,显示彩色图像和伪彩色深度图像
combined_image = np.hstack((color_data, depth_colormap))
cv2.imshow("Combined Image", combined_image)
# 按Esc键退出循环
key = cv2.waitKey(1)
if key == 27:
break
except RuntimeError as e:
print(f"等待帧时发生错误: {e}")
finally:
pipeline.stop()
cv2.destroyAllWindows()
代码二(实时显示鼠标点击出的距离信息,实时窗口和终端都显示):
import pyrealsense2 as rs
import numpy as np
import cv2
# 初始化深度相机
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
pipeline.start(config)
# 创建深度图像的伪彩色映射器
colorizer = rs.colorizer()
# 回调函数,处理鼠标点击事件
def on_mouse_click(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN: # 当左键被点击时
distance = depth_frame.get_distance(x, y) # 获取鼠标点击点的距离
distance_in_meters = round(distance, 2)
cv2.putText(combined_image, f"Distance: {distance_in_meters} m", (20, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
print(f"Distance at ({x}, {y}): {distance_in_meters}m") # 打印距离信息到终端
cv2.imshow("Combined Image", combined_image)
cv2.waitKey(100) # 显示距离文本的时间
# 创建一个窗口并设置鼠标回调函数
cv2.namedWindow("Combined Image")
cv2.setMouseCallback("Combined Image", on_mouse_click)
try:
while True:
try:
# 等待深度数据帧和RGB数据帧,设置等待时间为10秒
frames = pipeline.wait_for_frames(timeout_ms=10000)
depth_frame = frames.get_depth_frame()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
continue
color_data = np.asanyarray(color_frame.get_data())
depth_colormap = np.asanyarray(colorizer.colorize(depth_frame).get_data())
combined_image = np.hstack((color_data, depth_colormap))
cv2.imshow("Combined Image", combined_image)
key = cv2.waitKey(1)
if key == 27:
break
except RuntimeError as e:
print(f"等待帧时发生错误: {e}")
finally:
pipeline.stop()
cv2.destroyAllWindows()
二、深度相机保存左目和右目图像
import pyrealsense2 as rs
import numpy as np
import cv2
import os
import time
def get_color_images(left_save_dir, right_save_dir):
# 创建左目和右目的保存路径
if not os.path.exists(left_save_dir):
os.makedirs(left_save_dir)
if not os.path.exists(right_save_dir):
os.makedirs(right_save_dir)
# 配置和启动Realsense流
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) # 配置彩色流
pipeline.start(config)
try:
while True:
# 获取图像
frames = pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
# 将图像数据转换为OpenCV格式
color_image = None
if color_frame:
color_image = np.asanyarray(color_frame.get_data())
# 获取当前时间戳
t = time.time()
tname = str(t)[5:10] # 提取时间的秒数作为时间戳的名称
# 保存图像到左目和右目的不同文件夹,使用不同的文件名
left_image_name = 'left_color_image' + str(tname) + '.png'
right_image_name = 'right_color_image' + str(tname) + '.png'
cv2.imwrite(os.path.join(left_save_dir, left_image_name), color_image) # 保存左目彩色图像
cv2.imwrite(os.path.join(right_save_dir, right_image_name), color_image) # 保存右目彩色图像
# 实时显示彩色图像
cv2.imshow('RealSense Color Image', color_image)
# 等待1毫秒并检查是否按下Esc键
key = cv2.waitKey(1)
if key == 27: # 27是Esc键的ASCII码
break
finally:
# 停止数据流并销毁窗口
pipeline.stop()
cv2.destroyAllWindows()
if __name__ == "__main__":
left_save_dir = r"left_folder_path" # 保存左目彩色图像的文件夹路径
right_save_dir = r"right_folder_path" # 保存右目彩色图像的文件夹路径
get_color_images(left_save_dir, right_save_dir) # 获取并保存彩色图像