Drobotics logo DROBOTICSTechnical Library

Drone Guide

YOLO 实时人体检测:基础显示版

All Drone

YOLO Vision Code

YOLO 实时人体检测:基础显示版

打开摄像头后直接运行 YOLOv8 人体检测,并在 OpenCV 窗口显示检测框与 FPS。

这些脚本用于 DRF450 或机载计算机上的 OpenCV + YOLOv8 视觉识别测试。建议先在桌面或树莓派本地验证摄像头索引、模型路径和性能,再把检测结果接入 MAVLink、自主飞行或任务触发逻辑。

脚本目标

读取摄像头画面,使用 yolov8n.pt 检测 COCO person 类别,实时绘制人体框、置信度和 FPS。

运行依赖: Python、OpenCV、Ultralytics YOLO。检测脚本默认模型路径为 /home/drobotics/yolov8n.pt,部署时请确认模型文件存在。

学习重点

  • 适合桌面环境调试模型和摄像头
  • 保留完整画面尺寸进行推理
  • 按 q 键退出,便于现场演示

关键参数

参数当前设置
CAMERA_INDEX0
CONF_THRESHOLD0.5
PERSON_CLASS_ID0

运行前检查

  1. 安装依赖:pip install opencv-python ultralytics
  2. 确认摄像头编号,必要时修改 CAMERA_INDEXCAMERA_INDEXES
  3. 确认 YOLO 模型路径,例如 /home/drobotics/yolov8n.pt
  4. 在无人机上运行前,先单独验证摄像头、推理速度、保存路径和散热。

完整代码:show_video.py

import cv2
from ultralytics import YOLO
import time

# =========================
# SETTINGS
# =========================
CAMERA_INDEX = 0
CONF_THRESHOLD = 0.5

# =========================
# LOAD MODEL
# =========================
print(" Loading YOLOv8 model...")
model = YOLO("/home/drobotics/yolov8n.pt") # small + fast for Raspberry Pi

# COCO class 0 = person
PERSON_CLASS_ID = 0

# =========================
# CAMERA INIT
# =========================
cap = cv2.VideoCapture(CAMERA_INDEX)

if not cap.isOpened():
 print(" Cannot open camera")
 exit()

print(" Camera started... Press 'q' to quit")

prev_time = 0

# =========================
# MAIN LOOP
# =========================
while True:
 ret, frame = cap.read()
 if not ret:
 print(" Failed to read frame")
 break

 # YOLO inference
 results = model(frame, verbose=False)[0]

 # Draw detections
 for box in results.boxes:
 cls_id = int(box.cls[0])
 conf = float(box.conf[0])

 if cls_id == PERSON_CLASS_ID and conf > CONF_THRESHOLD:
 x1, y1, x2, y2 = map(int, box.xyxy[0])

 # draw box
 cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)

 label = f"Person {conf:.2f}"
 cv2.putText(frame, label, (x1, y1 - 10),
 cv2.FONT_HERSHEY_SIMPLEX, 0.5,
 (0, 255, 0), 2)

 # FPS calculation
 curr_time = time.time()
 fps = 1 / (curr_time - prev_time) if prev_time else 0
 prev_time = curr_time

 cv2.putText(frame, f"FPS: {fps:.2f}", (10, 30),
 cv2.FONT_HERSHEY_SIMPLEX, 1,
 (255, 0, 0), 2)

 # show frame
 cv2.imshow("Human Detection (YOLOv8)", frame)

 # quit key
 if cv2.waitKey(1) & 0xFF == ord('q'):
 break

cap.release()
cv2.destroyAllWindows()

下一步

先完成摄像头采集,再运行实时检测或无界面检测。后续可以把人体检测结果接入 MAVLink 任务逻辑,实现识别触发、悬停、返航、录像或地面站告警。

返回 DRF450 YOLO 章节