通过导入相关的检测模型后,就可以实现物体追踪与识别。
- import cv2
- import numpy as np
- import pyrealsense2 as rs
- from ultralytics import YOLO # 将YOLOv8导入到该py文件中
-
- # 加载官方或自定义模型
- model = YOLO(r"E:\Deep learning\YOLOv8\yolov8n.pt") # 加载一个官方的检测模型
- model = YOLO(r"E:\Deep learning\YOLOv8\yolov8s.pt") # 加载一个官方的检测模型
- # model = YOLO(r"E:\Deep learning\YOLOv8\yolov8n-seg.pt") # 加载一个官方的分割模型
- # model = YOLO(r"E:\Deep learning\YOLOv8\yolov8n-pose.pt") # 加载一个官方的姿态模型
-
-
- # 深度相机配置
- pipeline = rs.pipeline() # 定义流程pipeline,创建一个管道
- config = rs.config() # 定义配置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)
- pipe_profile = pipeline.start(config) # 启用管段流
- align = rs.align(rs.stream.color) # 这个函数用于将深度图像与彩色图像对齐
-
- def get_aligned_images(): # 定义一个获取图像帧的函数,返回深度和彩色数组
- frames = pipeline.wait_for_frames() # 等待获取图像帧
- depth_frame = frames.get_depth_frame() # 获取深度帧
- color_frame = frames.get_color_frame() # 获取对齐帧中的的color帧
- depth_image = np.asanyarray(depth_frame.get_data()) # 将深度帧转换为NumPy数组
- color_image = np.asanyarray(color_frame.get_data()) # 将彩色帧转化为numpy数组
- return depth_image, color_image
-
- if __name__ == '__main__':
- try:
- while True:
- img_depth, img_color = get_aligned_images() # 获取深度帧和彩色帧
- # cv2.applyColorMap()将深度图像转化为彩色图像,以便更好的可视化分析
- depth_colormap = cv2.applyColorMap(
- cv2.convertScaleAbs(img_depth, alpha=0.07), cv2.COLORMAP_JET)
- source = [img_color]
- # 轨迹追踪,persist=true表示数据储存
- results = model.track(source, persist=True)
- img_color = results[0].plot() # 在图像上添加色彩帧(追踪结果)
- # 将图像color_impage和depth_colormap水平堆叠
- # images = np.hstack((img_color, depth_colormap))
- # 设置窗口,窗口大小根据图像自动调整
- cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
- # 将图像images显示在窗口中,这个显示的是带有追踪结果的图像
- cv2.imshow('RealSense', img_color)
- key = cv2.waitKey(1) # 等待用户输入
- # Press esc or 'q' to close the image window
- if key & 0xFF == ord('q') or key == 27:
- cv2.destroyAllWindows()
- pipeline.stop()
- break
- finally:
- # Stop streaming
- pipeline.stop()
相关识别效果如下视频:
这里当人或者物体移动的时候,相应的识别框和标识也会跟着动。此外,如果采用了-Pose还可以识别人的姿态。
D435i相机+VScode+YOLOv8视频识别追踪