求基于RealSense D415与YOLOv8 best.pt的目标检测及深度角度代码
RealSense D415 + YOLOv8 目标检测与深度/角度获取方案
直接使用YOLOv8 best.pt的代码实现
无需转换模型格式,直接借助ultralytics库加载.pt模型,结合pyrealsense2调用RealSense相机,实现检测+深度/角度输出,代码如下:
import cv2 import pyrealsense2 as rs from ultralytics import YOLO import numpy as np # 加载训练好的YOLOv8模型 model = YOLO('best.pt') # 初始化RealSense相机管线 pipeline = rs.pipeline() config = rs.config() # 配置相机流(使用D415兼容的参数,避免启动报错) config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) # 启动相机 try: profile = pipeline.start(config) except RuntimeError as e: print(f"相机启动失败: {e}") print("请检查相机连接状态,或调整流参数为RealSense Viewer中显示的支持配置") exit() # 获取深度标尺(转换深度值为米) depth_sensor = profile.get_device().first_depth_sensor() depth_scale = depth_sensor.get_depth_scale() # 获取彩色相机内参(用于计算角度) intrinsics = profile.get_stream(rs.stream.color).as_video_stream_profile().get_intrinsics() try: while True: # 获取相机帧 frames = pipeline.wait_for_frames() color_frame = frames.get_color_frame() depth_frame = frames.get_depth_frame() if not color_frame or not depth_frame: continue # 转换为numpy数组 color_img = np.asanyarray(color_frame.get_data()) depth_img = np.asanyarray(depth_frame.get_data()) # YOLOv8目标检测 results = model(color_img) # 遍历检测结果,绘制框并计算深度/角度 for result in results: for box in result.boxes: # 提取边界框坐标、类别、置信度 x1, y1, x2, y2 = map(int, box.xyxy[0]) cls_idx = int(box.cls[0]) conf = float(box.conf[0]) label = f"{model.names[cls_idx]} {conf:.2f}" # 计算目标中心像素坐标 center_x = (x1 + x2) // 2 center_y = (y1 + y2) // 2 # 获取中心位置的深度值(单位:米) target_depth = depth_frame.get_distance(center_x, center_y) # 计算水平偏移角度(相对于相机光轴) angle_x = np.arctan((center_x - intrinsics.ppx) / intrinsics.fx) * 180 / np.pi # 在画面上绘制信息 cv2.rectangle(color_img, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(color_img, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2) info_text = f"Depth: {target_depth:.2f}m | Angle X: {angle_x:.2f}°" cv2.putText(color_img, info_text, (x1, y2+20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2) # 显示结果画面 cv2.imshow("YOLOv8 Detection + RealSense Depth", color_img) # 按ESC键退出循环 if cv2.waitKey(1) == 27: break finally: # 释放资源 pipeline.stop() cv2.destroyAllWindows()
依赖安装(非Anaconda环境)
直接用pip安装所需库:
pip install ultralyticspip install pyrealsense2
关键问题解决
相机启动报错
RuntimeError: Couldn't resolve requests
该错误源于配置的流参数(分辨率、帧率、格式)与相机不兼容。代码中已使用D415官方支持的640x480@30fps参数,若仍报错,可打开RealSense Viewer查看相机实际支持的流参数,替换代码中对应数值。深度值为0的情况
若目标深度显示为0,通常是目标处于相机深度检测范围外(过近/过远),或目标表面反光导致无法获取有效深度数据,可调整目标与相机的距离。
内容的提问来源于stack exchange,提问作者sleepy-puppy
相关产品推荐
相关产品推荐

