capture_and_detect.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """
  2. 抓取一枪机实时帧,使用当前配置的人体检测模型检测并保存标记图。
  3. 用于在 RK3588 上快速验证模型输出是否正常。
  4. """
  5. import os
  6. import sys
  7. import cv2
  8. import time
  9. import numpy as np
  10. from pathlib import Path
  11. sys.path.insert(0, str(Path(__file__).parent))
  12. from panorama_camera import ObjectDetector
  13. from config import DETECTION_CONFIG
  14. RTSP_URL = 'rtsp://admin:QAZwsx12@192.168.8.2:554/Streaming/Channels/101'
  15. OUT_DIR = Path('/home/admin/dsh/detection_check')
  16. OUT_DIR.mkdir(parents=True, exist_ok=True)
  17. def main():
  18. print(f"加载模型: {DETECTION_CONFIG['model_path']}")
  19. detector = ObjectDetector(
  20. model_path=DETECTION_CONFIG['model_path'],
  21. use_gpu=DETECTION_CONFIG.get('use_gpu', True),
  22. model_type=DETECTION_CONFIG.get('model_type', 'auto')
  23. )
  24. print(f"打开 RTSP: {RTSP_URL}")
  25. cap = cv2.VideoCapture(RTSP_URL, cv2.CAP_FFMPEG)
  26. cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
  27. if not cap.isOpened():
  28. print("无法打开 RTSP 流")
  29. return
  30. # 读取几帧清缓存
  31. for _ in range(10):
  32. cap.read()
  33. ret, frame = cap.read()
  34. cap.release()
  35. if not ret or frame is None:
  36. print("未获取到帧")
  37. return
  38. h, w = frame.shape[:2]
  39. print(f"帧尺寸: {w}x{h}")
  40. # 检测
  41. dets = detector.detect(frame)
  42. persons = [d for d in dets if d.class_name == 'person']
  43. print(f"检测到 {len(persons)} 个人 (原始目标 {len(dets)})")
  44. for i, p in enumerate(persons):
  45. print(f" {i}: conf={p.confidence:.3f} bbox={p.bbox} center={p.center}")
  46. # 保存原图
  47. orig_path = OUT_DIR / 'capture_original.jpg'
  48. cv2.imwrite(str(orig_path), frame)
  49. # 绘制标记图
  50. marked = frame.copy()
  51. for p in persons:
  52. x, y, bw, bh = p.bbox
  53. cv2.rectangle(marked, (x, y), (x + bw, y + bh), (0, 255, 0), 2)
  54. label = f"person {p.confidence:.2f}"
  55. cv2.putText(marked, label, (x, max(y - 5, 20)),
  56. cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
  57. marked_path = OUT_DIR / 'capture_marked.jpg'
  58. cv2.imwrite(str(marked_path), marked)
  59. print(f"已保存: {orig_path}, {marked_path}")
  60. detector.release()
  61. if __name__ == '__main__':
  62. main()