
本文详解如何在 Raspberry Pi 上基于 TensorFlow Lite Object Detection 模型实现“检测到人即触发报警”的功能,包括修复 DetectionResult 不可迭代的常见错误、集成音频提示与高亮边框可视化,并提供完整可运行代码。
本文详解如何在 raspberry pi 上基于 tensorflow lite object detection 模型实现“检测到人即触发报警”的功能,包括修复 `detectionresult` 不可迭代的常见错误、集成音频提示与高亮边框可视化,并提供完整可运行代码。
在基于 TensorFlow Lite 的实时目标检测项目中(如使用 efficientdet_lite0.tflite 在树莓派 4 上进行人体识别),开发者常希望在检测到特定目标(如 "person")时触发多模态报警——例如播放警示音效、叠加红色边框或闪烁提示。但初学者容易在遍历检测结果时遇到关键错误:TypeError: 'DetectionResult' object is not iterable。
该错误的根本原因在于:detector.detect() 返回的是 vision.DetectionResult 对象,而非直接的检测列表。它是一个封装类,其实际检测结果存储在 .detections 属性中,该属性才是一个 List[Detection] 类型的可迭代对象。因此,原始代码中:
for obj in detection_result: # ❌ 错误:DetectionResult 不支持直接 for 循环
必须修正为:
for obj in detection_result.detections: # ✅ 正确:遍历 detections 列表
这是调用 TFLite Support Library 进行目标检测时最关键的结构认知点,也是后续所有逻辑(如标签匹配、报警触发)的前提。
以下为修复后的核心报警逻辑片段(已整合进完整流程):
# 检查是否检测到指定标签(如 'person')
alarm_triggered = False
if detection_result.detections: # 安全检查:确保 detections 非空
for detection in detection_result.detections:
if detection.categories and detection.categories[0].category_name == alarm_label:
alarm_triggered = True
break # 找到即退出,避免重复触发
# 触发多模态报警
if alarm_triggered:
# ? 音频报警(需提前初始化 pygame.mixer)
try:
alarm_sound.play()
except Exception as e:
print(f"[WARN] Audio playback failed: {e}")
# ?️ 视觉报警:绘制加粗红色边框
cv2.rectangle(image, (0, 0), (width - 1, height - 1), (0, 0, 255), 4)
⚠️ 注意事项:
- detection.categories 是一个列表(即使只返回一个类别),务必通过 detection.categories[0].category_name 访问标签名,避免索引错误;
- 建议添加 if detection_result.detections: 空值检查,防止无检测结果时异常;
- 树莓派上 pygame.mixer 对 WAV 文件兼容性较好,推荐使用单声道、16kHz、PCM 编码的 .wav 文件(如 alarm1.wav),避免因音频格式不支持导致 play() 静默失败;
- 若需防抖动报警(避免连续帧重复触发),可引入计时器或状态去抖逻辑,例如仅在间隔 ≥1.5 秒后再次触发;
- cv2.rectangle 绘制边框时注意坐标范围:width 和 height 应与 cap.set() 设置的实际帧尺寸一致,否则边框可能错位。
最后,确保依赖已正确安装(适用于 Raspbian Bullseye):
pip3 install opencv-python-headless numpy tflite-support pygame # 如使用 Edge TPU,额外安装: # apt-get install libatlas-base-dev libhdf5-dev libhdf5-serial-dev libhdf5-cpp-103 # pip3 install tflite-runtime
运行时可通过命令行灵活配置报警标签与硬件参数:
python3 detect_and_alarm.py \ --model efficientdet_lite0.tflite \ --alarmLabel person \ --frameWidth 640 \ --frameHeight 480 \ --numThreads 2
至此,你已构建了一个稳定、低延迟、具备声光反馈能力的人体检测报警系统,可直接部署于树莓派等边缘设备,适用于安防监控、智能门禁等实用场景。











