Drobotics logo DROBOTICSTechnical Library

Drone Guide

YOLO 前置准备:USB 摄像头连续拍照采集

All Drone

YOLO Vision Code

YOLO 前置准备:USB 摄像头连续拍照采集

使用 OpenCV 自动查找可用摄像头,并按固定间隔保存图片,用于快速验证相机和采集训练样本。

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

脚本目标

遍历 0 到 4 号摄像头索引,打开可用摄像头后每 0.5 秒保存一张 JPG 图片到当前目录。

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

学习重点

  • 适合先验证摄像头是否可用
  • 可快速采集 YOLO 训练或测试图片
  • 脚本结构简单,便于修改保存目录和采集间隔

关键参数

参数当前设置
CAMERA_INDEXES[0, 1, 2, 3, 4]
INTERVAL0.5 # seconds between photos
SAVE_DIRos.getcwd() # save photos in the current folder

运行前检查

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

完整代码:capture_photos.py

import cv2
import time
import os

# =========================
# SETTINGS
# =========================
CAMERA_INDEXES = [0, 1, 2, 3, 4]
INTERVAL = 0.5 # seconds between photos
SAVE_DIR = os.getcwd() # save photos in the current folder


# =========================
# CAMERA INIT
# =========================
def open_camera(camera_indexes):
 for index in camera_indexes:
 print(f"Trying camera index {index}...")

 cap = cv2.VideoCapture(index)

 if cap.isOpened():
 ret, frame = cap.read()
 if ret and frame is not None:
 print(f"Camera opened successfully at index {index}")
 return cap, index

 cap.release()

 return None, None


cap, camera_index = open_camera(CAMERA_INDEXES)

if cap is None:
 print("Cannot open any camera")
 exit()

print("Camera started")
print(f"Using camera index: {camera_index}")
print(f"Saving images to: {SAVE_DIR}")
print("Press Ctrl+C to stop")

# =========================
# CAPTURE LOOP
# =========================
count = 0

try:
 while True:
 ret, frame = cap.read()

 if not ret or frame is None:
 print("Failed to read frame")
 break

 filename = os.path.join(
 SAVE_DIR,
 f"image_{count:06d}.jpg"
 )

 saved = cv2.imwrite(filename, frame)

 if saved:
 print(f"Saved: {filename}")
 else:
 print(f"Failed to save: {filename}")

 count += 1
 time.sleep(INTERVAL)

except KeyboardInterrupt:
 print("\nStopped by user")

finally:
 cap.release()
 print("Camera released")

下一步

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

返回 DRF450 YOLO 章节