YOLO11解决方案之速度估算探索
概述
Ultralytics提供了一系列的解决方案,利用YOLO11解决现实世界的问题,包括物体计数、模糊处理、热力图、安防系统、速度估计、物体追踪等多个方面的应用。
YOLO速度估算结合物体检测和跟踪技术,使用YOLO11 模型检测每帧中的物体,跨帧跟踪这些物体,计算它们在一段时间内的移动情况,然后利用物体在帧间移动的距离和帧频来估算其速度。可为交通分析、自动驾驶、安全分析等各种场景提供高效的速度估计。本文使用Python实现了简单的演示界面,可以在图像中画线或者框,运行推理,输出叠加了类别和速度的视频。
Ultralytics提供了CLI和Python例子,展示如何使用速度估算解决方案。
CLI:
# Run a speed example
yolo solutions speed show=True# Pass a source video
yolo solutions speed source="path/to/video.mp4"# Adjust meter per pixel value based on camera configuration
yolo solutions speed meter_per_pixel=0.05
Python:
import cv2from ultralytics import solutionscap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"# Video writer
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
video_writer = cv2.VideoWriter("speed_management.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))# Initialize speed estimation object
speedestimator = solutions.SpeedEstimator(show=True, # display the outputmodel="yolo11n.pt", # path to the YOLO11 model file.fps=fps, # adjust speed based on frame per second# max_speed=120, # cap speed to a max value (km/h) to avoid outliers# max_hist=5, # minimum frames object tracked before computing speed# meter_per_pixel=0.05, # highly depends on the camera configuration# classes=[0, 2], # estimate speed of specific classes.# line_width=2, # adjust the line width for bounding boxes
)# Process video
while cap.isOpened():success, im0 = cap.read()if not success:print("Video frame is empty or processing is complete.")breakresults = speedestimator(im0)# print(results) # access the outputvideo_writer.write(results.plot_im) # write the processed frame.cap.release()
video_writer.release()
cv2.destroyAllWindows() # destroy all opened windows
SpeedEstimator参数
基本参数
名称 | 类型 | 默认值 | 说明 |
---|---|---|---|
model | str | None | YOLO Model 文件路径. |
fps | float | 30.0 | 视频帧率. |
max_hist | int | 5 | 跟踪物体进行速度/方向计算的最多历史点数. |
meter_per_pixel | float | 0.05 | 缩放因子,用于将像素距离转换为实际单位。 |
max_speed | int | 120 | 视觉叠加中的最高限速(用于警报)。 |
SpeedEstimator支持使用track参数:
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
tracker | str | 'botsort.yaml' | 指定要使用的跟踪算法, bytetrack.yaml 或 botsort.yaml . |
conf | float | 0.3 | 设置检测的置信度阈值;数值越低,跟踪的物体越多,但可能会出现误报。 |
iou | float | 0.5 | 设置交叉重叠 (IoU) 阈值,用于过滤重叠检测。 |
classes | list | None | 按类别索引筛选结果。例如 classes=[0, 2, 3] 只跟踪指定的类别(class在COCO数据集定义)。 |
verbose | bool | True | 控制跟踪结果的显示,提供被跟踪物体的可视化输出。 |
device | str | None | 指定用于推理的设备(例如: cpu , cuda:0 或 0 ). 允许用户选择CPU 、特定GPU 或其他计算设备运行模型。 |
可视化参数:
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
show | bool | False | 如果 True 在一个窗口中显示注释的图像或视频。有助于在开发或测试过程中提供即时视觉反馈。 |
line_width | None or int | None | 指定边界框的线宽。如果 None 则根据图像大小自动调整线宽,使图像更加清晰。 |
show_conf | bool | True | 在标签旁显示每次检测的置信度得分。让人了解模型对每次检测的确定性。 |
show_labels | bool | True | 在可视输出中显示每次检测的标签。让用户立即了解检测到的物体。 |
GUI演示
这里使用Tkinter编写一个简单界面,演示速度估算应用。
从文件菜单打开一个mp4文件,显示第一帧图像。
在图像上画检测线或者检测框。
矩形绘制完成后,可以使用鼠标右键拖动改变角度。
然后“开始演示”,物体名称及其速度叠加在跟踪物体上方。
如果verbose
为True
,控制台输出当前帧的信息。
0: 384x640 15 cars, 24.0ms
Speed: 1.7ms preprocess, 24.0ms inference, 2.2ms postprocess per image at shape (1, 3, 384, 640)
🚀 Results ****: SolutionResults(out_count=9, classwise_count={'car': {'IN': 0, 'OUT': 8}, 'bus': {'IN': 0, 'OUT': 1}, 'truck': {'IN': 0, 'OUT': 0}}, total_tracks=15)
GUI演示程序代码
本演示程序定义了两个类:VideoProcessorApp类和VideoProcessor类。
class VideoProcessorApp:def __init__(self, root):self.root = rootself.root.title("视频处理应用演示")self.root.geometry("900x700")# 设置中文字体self.font = ('SimHei', 10)# 视频和图像处理相关变量self.cap = Noneself.video_path = ""self.original_frame = Noneself.current_frame = Noneself.processed_frames = []self.is_playing = Falseself.is_processing = Falseself.is_paused = Falseself.draw_mode = None # 'line' 或 'rectangle'self.start_point = Noneself.end_point = Noneself.drawing = Falseself.output_file = ""self.rect_angle = 0 # 矩形旋转角度self.rect_center = None # 矩形中心点self.rect_points = None # 矩形四个顶点self.pause_event = threading.Event()self.video_processor = Noneself._dt_buffer = []self._last_time = time.perf_counter()self.count = 0self.count_read = 0self.frame_reading_done = False # 标志位self.object_count = {}# 多线程相关self.frame_queue = Queue(maxsize=60)self.result_queue = Queue(maxsize=60)self.writer_queue = Queue(maxsize=60)self.stop_threads = False# 创建界面组件self.create_menu()self.create_widgets()# 绑定鼠标事件self.canvas.bind("<Button-1>", self.on_mouse_click)self.canvas.bind("<B1-Motion>", self.on_mouse_drag)self.canvas.bind("<ButtonRelease-1>", self.on_mouse_release)self.canvas.bind("<Button-3>", self.on_right_click)self.canvas.bind("<B3-Motion>", self.on_right_drag)self.canvas.bind("<ButtonRelease-3>", self.on_right_release)
VideoProcessor类专门处理视频帧,其中调用了solutions.SpeedEstimator类:
self.speedestimator = solutions.SpeedEstimator(show=False,model="yolo11n.pt",region=pts,fps=fps, # adjust speed based on fpsclasses=[2,5,7],verbose = False,)
由于读写视频文件和进行神经网络推理均需要较大的计算量,本演示代码使用多线程分别处理读、写、显示和推理,以最大化利用计算机资源,提高处理速度。
def start_processing(self):if self.cap is None or not self.cap.isOpened():messagebox.showerror("错误", "请先打开视频文件")returnif self.video_processor is None:messagebox.showerror("错误", "请先绘制线条或矩形")returnif self.is_processing:messagebox.showinfo("提示", "正在处理视频,请等待")returnself.processed_frames.clear()self.is_processing = Trueself.is_playing = Trueself.is_paused = Falseself.stop_threads = Falseself.process_button.config(state=tk.DISABLED)self.pause_button.config(state=tk.NORMAL)self.stop_button.config(state=tk.NORMAL)self.pause_event.set()# 启动多线程self.reader_thread = threading.Thread(target=self.frame_reader)self.processor_thread = threading.Thread(target=self.frame_processor)self.display_thread = threading.Thread(target=self.result_display)self.writer_thread = threading.Thread(target=self.video_writer_worker)# 设置线程优先级try:self.reader_thread.priority = 'ABOVE_NORMAL'self.processor_thread.priority = 'HIGH'self.writer_thread.priority = 'ABOVE_NORMAL'except:pass# 启动线程self.reader_thread.start()self.processor_thread.start()self.display_thread.start()self.writer_thread.start()
其中的推理线程代码如下:
def frame_processor(self):"""专用模型推理线程"""while not self.stop_threads:if self.is_paused:time.sleep(0.01)continuetry:start_time = time.time()frame = self.frame_queue.get(timeout=0.1)processed, self.object_count = self.video_processor.process_frame(frame)self.count += 1if not self.stop_threads:self.result_queue.put(processed, timeout=0.1)except Empty:continueexcept Exception as e:print(f"Frame processor error: {str(e)}")break
依据计算机视觉技术估算的速度并非精确的速度,不同的图像和其他因素,会造成不同的估算速度差异,在实际应用中,需要使用测速雷达等设备进行标定,调整计算参数,才能有实用价值。