panorama_camera.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. """
  2. 全景摄像头模块
  3. 负责获取视频流和物体检测
  4. """
  5. import os
  6. # 必须在导入cv2之前设置,防止FFmpeg多线程解码崩溃
  7. # pthread_frame.c:167 async_lock assertion
  8. os.environ['OPENCV_FFMPEG_CAPTURE_OPTIONS'] = 'rtsp_transport;tcp|threads;1'
  9. import cv2
  10. import numpy as np
  11. import threading
  12. import queue
  13. import time
  14. import logging
  15. from datetime import datetime
  16. from typing import Optional, List, Tuple, Dict, Any
  17. from dataclasses import dataclass
  18. from pathlib import Path
  19. from config import PANORAMA_CAMERA, DETECTION_CONFIG
  20. from config.camera import parse_resolution
  21. from dahua_sdk import DahuaSDK, PTZCommand
  22. from video_lock import safe_read, safe_is_opened
  23. from inference_backend import nms
  24. logger = logging.getLogger(__name__)
  25. @dataclass
  26. class DetectedObject:
  27. """检测到的物体"""
  28. class_name: str # 类别名称
  29. confidence: float # 置信度
  30. bbox: Tuple[int, int, int, int] # 边界框 (x, y, width, height)
  31. center: Tuple[int, int] # 中心点坐标
  32. track_id: Optional[int] = None # 跟踪ID
  33. class PanoramaCamera:
  34. """全景摄像头类"""
  35. def __init__(self, sdk: DahuaSDK, camera_config: Dict = None):
  36. """
  37. 初始化全景摄像头
  38. Args:
  39. sdk: 大华SDK实例
  40. camera_config: 摄像头配置
  41. """
  42. self.sdk = sdk
  43. self.config = camera_config or PANORAMA_CAMERA
  44. # 解析期望分辨率
  45. self.frame_width, self.frame_height = parse_resolution(self.config.get('resolution'))
  46. # 摄像头品牌 / SDK 使用策略
  47. # brand: 'dahua' | 'hikvision' | 'uniview' | 'auto'
  48. # use_sdk: True 时使用大华 SDK 登录;False 时仅使用 RTSP 取流
  49. self.brand = self.config.get('brand', 'auto').lower()
  50. self.use_sdk = self.config.get('use_sdk', self.brand != 'hikvision')
  51. if self.brand == 'hikvision':
  52. self.use_sdk = False
  53. self.login_handle = None
  54. self.play_handle = None
  55. self.connected = False
  56. # 视频流
  57. self.frame_queue = queue.Queue(maxsize=10)
  58. self.current_frame = None
  59. self.frame_lock = threading.Lock()
  60. self.rtsp_cap = None # RTSP视频捕获
  61. self._camera_id = 'panorama' # 用于per-camera锁
  62. # 检测器
  63. self.detector = None
  64. # 控制标志
  65. self.running = False
  66. self.stream_thread = None
  67. # 断线重连
  68. self.auto_reconnect = True
  69. self.reconnect_interval = 5.0 # 重连间隔(秒)
  70. self.max_reconnect_attempts = 3 # 最大重连次数
  71. def connect(self) -> bool:
  72. """
  73. 连接摄像头
  74. Returns:
  75. 是否成功
  76. """
  77. if not self.use_sdk:
  78. print(f"[PanoramaCamera] {self.config.get('ip')} 配置为 RTSP-only 模式,跳过 SDK 登录")
  79. self.connected = True
  80. return True
  81. login_handle, error = self.sdk.login(
  82. self.config['ip'],
  83. self.config['port'],
  84. self.config['username'],
  85. self.config['password']
  86. )
  87. if login_handle is None:
  88. print(f"连接全景摄像头失败: IP={self.config['ip']}, 错误码={error}")
  89. return False
  90. self.login_handle = login_handle
  91. self.connected = True
  92. print(f"成功连接全景摄像头: {self.config['ip']}")
  93. return True
  94. def disconnect(self):
  95. """断开连接"""
  96. self.stop_stream()
  97. if self.use_sdk and self.login_handle:
  98. self.sdk.logout(self.login_handle)
  99. self.login_handle = None
  100. self.connected = False
  101. def is_connected(self) -> bool:
  102. """是否已连接"""
  103. return self.connected
  104. def start_stream(self) -> bool:
  105. """
  106. 开始视频流 (SDK 模式,仅 Dahua 等品牌支持)
  107. Returns:
  108. 是否成功
  109. """
  110. if not self.connected:
  111. return False
  112. if not self.use_sdk:
  113. print("[PanoramaCamera] 当前为 RTSP-only 模式,跳过 SDK 视频流")
  114. return False
  115. self.play_handle = self.sdk.real_play(
  116. self.login_handle,
  117. self.config['channel']
  118. )
  119. if self.play_handle is None:
  120. print("启动视频流失败")
  121. return False
  122. self.running = True
  123. self.stream_thread = threading.Thread(target=self._stream_worker, daemon=True)
  124. self.stream_thread.start()
  125. print("视频流已启动")
  126. return True
  127. def start_stream_rtsp(self, rtsp_url: str = None) -> bool:
  128. if rtsp_url is None:
  129. rtsp_url = self.config.get('rtsp_url') or f"rtsp://{self.config['username']}:{self.config['password']}@{self.config['ip']}:{self.config.get('rtsp_port', 554)}/h264/ch{self.config['channel']}/main/av_stream"
  130. try:
  131. # 先尝试FFmpeg后端
  132. self.rtsp_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
  133. if not self.rtsp_cap.isOpened():
  134. # FFmpeg失败,尝试GStreamer后端
  135. print(f"FFmpeg后端无法打开RTSP流,尝试GStreamer后端...")
  136. try:
  137. gst_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_GSTREAMER)
  138. if gst_cap.isOpened():
  139. self.rtsp_cap = gst_cap
  140. print(f"使用GStreamer后端打开RTSP流成功")
  141. else:
  142. print(f"无法打开RTSP流: {rtsp_url}")
  143. return False
  144. except Exception as ge:
  145. print(f"GStreamer后端也不可用: {ge}")
  146. return False
  147. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
  148. self.running = True
  149. self.stream_thread = threading.Thread(target=self._rtsp_stream_worker, daemon=True)
  150. self.stream_thread.start()
  151. print(f"RTSP视频流已启动: {rtsp_url} (期望分辨率 {self.frame_width}x{self.frame_height})")
  152. return True
  153. except Exception as e:
  154. print(f"RTSP流启动失败: {e}")
  155. return False
  156. def _stream_worker(self):
  157. """视频流工作线程 (SDK模式)"""
  158. retry_count = 0
  159. max_retries = 10
  160. while self.running:
  161. try:
  162. # 尝试从 SDK 帧缓冲区获取帧 (如果可用)
  163. frame_buffer = self.sdk.get_video_frame_buffer(self.config['channel'])
  164. if frame_buffer:
  165. frame_info = frame_buffer.get(timeout=0.1)
  166. if frame_info and frame_info.get('data'):
  167. # 解码帧数据 (如果需要)
  168. # 注意: SDK回调返回的是编码数据,需要解码
  169. # 这里暂时跳过,因为解码需要额外处理
  170. pass
  171. # RTSP 模式获取帧 (推荐方式)
  172. if self.rtsp_cap is not None and safe_is_opened(self.rtsp_cap, self._camera_id):
  173. ret, frame = safe_read(self.rtsp_cap, self._camera_id)
  174. if ret and frame is not None:
  175. with self.frame_lock:
  176. self.current_frame = frame.copy()
  177. try:
  178. self.frame_queue.put(frame.copy(), block=False)
  179. except queue.Full:
  180. pass
  181. retry_count = 0 # 重置重试计数
  182. time.sleep(0.001) # 减少CPU占用
  183. continue
  184. # 如果 RTSP 不可用,尝试自动连接
  185. if retry_count < max_retries:
  186. rtsp_url = self._build_rtsp_url()
  187. try:
  188. if self.rtsp_cap is None:
  189. self.rtsp_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
  190. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) # 减少缓冲延迟
  191. if safe_is_opened(self.rtsp_cap, self._camera_id):
  192. retry_count = 0
  193. continue
  194. except Exception as e:
  195. pass
  196. retry_count += 1
  197. time.sleep(1.0) # 重试间隔
  198. else:
  199. # 超过最大重试次数,使用与配置分辨率一致的模拟帧
  200. frame = np.zeros((self.frame_height, self.frame_width, 3), dtype=np.uint8)
  201. with self.frame_lock:
  202. self.current_frame = frame
  203. try:
  204. self.frame_queue.put(frame, block=False)
  205. except queue.Full:
  206. pass
  207. time.sleep(0.1)
  208. except Exception as e:
  209. err_str = str(e)
  210. if 'async_lock' in err_str or 'Assertion' in err_str:
  211. print(f"视频流FFmpeg内部错误,重建连接: {e}")
  212. self._reconnect_rtsp()
  213. else:
  214. print(f"视频流错误: {e}")
  215. time.sleep(0.5)
  216. def _build_rtsp_url(self) -> str:
  217. return self.config.get('rtsp_url') or f"rtsp://{self.config['username']}:{self.config['password']}@{self.config['ip']}:{self.config.get('rtsp_port', 554)}/h264/ch{self.config['channel']}/main/av_stream"
  218. def _rtsp_stream_worker(self):
  219. """RTSP视频流工作线程"""
  220. import signal
  221. # 屏蔽SIGINT在此线程,由主线程处理
  222. if hasattr(signal, 'pthread_sigmask'):
  223. try:
  224. signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT})
  225. except (AttributeError, OSError):
  226. pass
  227. max_consecutive_errors = 50
  228. error_count = 0
  229. while self.running:
  230. try:
  231. if self.rtsp_cap is None or not safe_is_opened(self.rtsp_cap, self._camera_id):
  232. time.sleep(0.1)
  233. continue
  234. ret, frame = safe_read(self.rtsp_cap, self._camera_id)
  235. if not ret or frame is None:
  236. error_count += 1
  237. if error_count > max_consecutive_errors:
  238. print(f"全景RTSP流连续{max_consecutive_errors}次读取失败,尝试重连...")
  239. self._reconnect_rtsp()
  240. error_count = 0
  241. time.sleep(0.01)
  242. continue
  243. error_count = 0
  244. # 记录实际分辨率,仅做校验与提示(不做拉伸缩放,避免丢精度)
  245. actual_h, actual_w = frame.shape[:2]
  246. if not getattr(self, '_resolution_logged', False):
  247. print(f"全景摄像头实际分辨率: {actual_w}x{actual_h},期望分辨率: "
  248. f"{self.frame_width}x{self.frame_height}")
  249. self._resolution_logged = True
  250. if (actual_w, actual_h) != (self.frame_width, self.frame_height):
  251. if not getattr(self, '_resolution_warned', False):
  252. logger.warning(
  253. f"全景摄像头分辨率 {actual_w}x{actual_h} 与期望分辨率 "
  254. f"{self.frame_width}x{self.frame_height} 不一致,"
  255. f"模型推理时将使用 letterbox 灰度填充保持比例"
  256. )
  257. self._resolution_warned = True
  258. with self.frame_lock:
  259. self.current_frame = frame.copy()
  260. try:
  261. self.frame_queue.put(frame, block=False)
  262. except queue.Full:
  263. pass
  264. except Exception as e:
  265. err_str = str(e)
  266. if 'async_lock' in err_str or 'Assertion' in err_str:
  267. print(f"全景RTSP流FFmpeg内部错误,3秒后重建连接: {e}")
  268. time.sleep(3)
  269. self._reconnect_rtsp()
  270. else:
  271. print(f"全景RTSP视频流错误: {e}")
  272. time.sleep(0.5)
  273. def _reconnect_rtsp(self):
  274. """重建RTSP连接"""
  275. rtsp_url = self._build_rtsp_url()
  276. if self.rtsp_cap is not None:
  277. try:
  278. self.rtsp_cap.release()
  279. except Exception:
  280. pass
  281. self.rtsp_cap = None
  282. time.sleep(1)
  283. try:
  284. self.rtsp_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
  285. if safe_is_opened(self.rtsp_cap, self._camera_id):
  286. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
  287. print("全景RTSP流重连成功")
  288. else:
  289. print("全景RTSP流重连失败")
  290. self.rtsp_cap = None
  291. except Exception as e:
  292. print(f"全景RTSP流重连异常: {e}")
  293. self.rtsp_cap = None
  294. def stop_stream(self):
  295. """停止视频流"""
  296. self.running = False
  297. if self.stream_thread:
  298. self.stream_thread.join(timeout=2)
  299. if self.play_handle:
  300. self.sdk.stop_real_play(self.play_handle)
  301. self.play_handle = None
  302. if self.rtsp_cap:
  303. self.rtsp_cap.release()
  304. self.rtsp_cap = None
  305. def get_frame(self) -> Optional[np.ndarray]:
  306. """
  307. 获取当前帧
  308. Returns:
  309. 当前帧图像
  310. """
  311. with self.frame_lock:
  312. return self.current_frame.copy() if self.current_frame is not None else None
  313. def get_frame_from_queue(self, timeout: float = 0.1) -> Optional[np.ndarray]:
  314. """
  315. 从帧队列获取帧 (用于批量处理)
  316. Args:
  317. timeout: 等待超时时间
  318. Returns:
  319. 帧图像或None
  320. """
  321. try:
  322. return self.frame_queue.get(timeout=timeout)
  323. except:
  324. return None
  325. def get_frame_buffer(self, count: int = 5) -> List[np.ndarray]:
  326. """
  327. 获取帧缓冲 (用于运动检测等需要多帧的场景)
  328. Args:
  329. count: 获取帧数
  330. Returns:
  331. 帧列表
  332. """
  333. frames = []
  334. while len(frames) < count:
  335. frame = self.get_frame_from_queue(timeout=0.05)
  336. if frame is not None:
  337. frames.append(frame)
  338. else:
  339. break
  340. return frames
  341. def set_detector(self, detector):
  342. """设置物体检测器"""
  343. self.detector = detector
  344. def detect_objects(self, frame: np.ndarray = None) -> List[DetectedObject]:
  345. """
  346. 检测物体
  347. Args:
  348. frame: 输入帧,如果为None则使用当前帧
  349. Returns:
  350. 检测到的物体列表
  351. """
  352. if frame is None:
  353. frame = self.get_frame()
  354. if frame is None or self.detector is None:
  355. return []
  356. return self.detector.detect(frame)
  357. def get_detection_position(self, obj: DetectedObject,
  358. frame_size: Tuple[int, int]) -> Tuple[float, float]:
  359. """
  360. 获取检测物体在画面中的相对位置
  361. Args:
  362. obj: 检测到的物体
  363. frame_size: 画面尺寸 (width, height)
  364. Returns:
  365. 相对位置 (x_ratio, y_ratio) 范围0-1
  366. """
  367. width, height = frame_size
  368. x_ratio = obj.center[0] / width
  369. y_ratio = obj.center[1] / height
  370. return (x_ratio, y_ratio)
  371. class ObjectDetector:
  372. """
  373. 物体检测器
  374. 使用YOLO11模型进行人体检测
  375. 支持 YOLO (.pt), RKNN (.rknn), ONNX (.onnx) 模型
  376. """
  377. def __init__(self, model_path: str = None, use_gpu: bool = True, model_size: str = 'n',
  378. model_type: str = 'auto'):
  379. """
  380. 初始化检测器
  381. Args:
  382. model_path: 模型路径 (支持 .pt, .rknn, .onnx)
  383. use_gpu: 是否使用GPU
  384. model_size: 模型尺寸 ('n', 's', 'm', 'l', 'x') - 仅 YOLO 模型有效
  385. model_type: 模型类型 ('auto', 'yolo', 'rknn', 'onnx')
  386. """
  387. self.model = None
  388. self.rknn_detector = None
  389. self.model_path = model_path
  390. self.use_gpu = use_gpu
  391. self.model_size = model_size
  392. self.model_type = model_type
  393. self.is_end2end = False
  394. self.config = DETECTION_CONFIG
  395. self.device = 'cuda:0' if use_gpu else 'cpu'
  396. # 检测图片保存配置
  397. self._save_image_enabled = self.config.get('save_detection_image', False)
  398. self._image_save_dir = Path(self.config.get('detection_image_dir', './detection_images'))
  399. self._image_max_count = self.config.get('detection_image_max_count', 1000)
  400. self._last_save_time = 0
  401. # 保存间隔:优先使用配置值,否则基于检测帧率计算(检测间隔的1.5倍)
  402. detection_fps = self.config.get('detection_fps', 2)
  403. self._save_interval = self.config.get('save_interval', 1.5 / detection_fps)
  404. # 创建保存目录
  405. if self._save_image_enabled:
  406. self._ensure_save_dir()
  407. # 根据扩展名自动判断模型类型
  408. if model_path:
  409. ext = os.path.splitext(model_path)[1].lower()
  410. if ext == '.rknn':
  411. self.model_type = 'rknn'
  412. elif ext == '.onnx':
  413. self.model_type = 'onnx'
  414. elif ext == '.pt':
  415. self.model_type = 'yolo'
  416. # end2end 模型(内置NMS),输出格式 (N, 6) = (x1,y1,x2,y2,conf,cls)
  417. if 'end2end' in os.path.basename(model_path).lower():
  418. self.is_end2end = True
  419. self._load_model()
  420. def _load_model(self):
  421. """加载检测模型"""
  422. if self.model_type == 'rknn':
  423. self._load_rknn_model()
  424. elif self.model_type == 'onnx':
  425. self._load_onnx_model()
  426. else:
  427. self._load_yolo_model()
  428. def _load_rknn_model(self):
  429. """加载 RKNN 模型"""
  430. if not self.model_path:
  431. raise ValueError("RKNN 模型需要指定 model_path")
  432. try:
  433. from rknnlite.api import RKNNLite
  434. self.rknn = RKNNLite()
  435. ret = self.rknn.load_rknn(self.model_path)
  436. if ret != 0:
  437. raise RuntimeError(f"加载 RKNN 模型失败: {self.model_path}")
  438. ret = self.rknn.init_runtime(core_mask=RKNNLite.NPU_CORE_0_1_2)
  439. if ret != 0:
  440. raise RuntimeError(f"初始化 RKNN 运行时失败")
  441. print(f"RKNN 模型加载成功: {self.model_path}")
  442. except ImportError:
  443. raise ImportError("未安装 rknnlite,请运行: pip install rknnlite2")
  444. def _load_onnx_model(self):
  445. """加载 ONNX 模型"""
  446. if not self.model_path:
  447. raise ValueError("ONNX 模型需要指定 model_path")
  448. try:
  449. import onnxruntime as ort
  450. self.session = ort.InferenceSession(self.model_path)
  451. self.input_name = self.session.get_inputs()[0].name
  452. self.output_names = [o.name for o in self.session.get_outputs()]
  453. print(f"ONNX 模型加载成功: {self.model_path}, 输出数量={len(self.output_names)}")
  454. except ImportError:
  455. raise ImportError("未安装 onnxruntime,请运行: pip install onnxruntime")
  456. def _load_yolo_model(self):
  457. """加载YOLO11检测模型"""
  458. try:
  459. from ultralytics import YOLO
  460. if self.model_path:
  461. self.model = YOLO(self.model_path)
  462. else:
  463. model_name = f'yolo11{self.model_size}.pt'
  464. self.model = YOLO(model_name)
  465. dummy = np.zeros((640, 640, 3), dtype=np.uint8)
  466. self.model(dummy, device=self.device, verbose=False)
  467. print(f"成功加载YOLO11检测模型 (device={self.device})")
  468. except ImportError:
  469. print("未安装ultralytics,请运行: pip install ultralytics")
  470. self._load_opencv_model()
  471. except Exception as e:
  472. print(f"加载YOLO11模型失败: {e}")
  473. self._load_opencv_model()
  474. def _load_opencv_model(self):
  475. """使用OpenCV加载模型"""
  476. pass
  477. def _ensure_save_dir(self):
  478. """确保保存目录存在"""
  479. try:
  480. self._image_save_dir.mkdir(parents=True, exist_ok=True)
  481. logger.info(f"检测图片保存目录: {self._image_save_dir}")
  482. except Exception as e:
  483. logger.error(f"创建检测图片目录失败: {e}")
  484. self._save_image_enabled = False
  485. def _cleanup_old_images(self):
  486. """清理旧图片,保持目录下图片数量不超过上限"""
  487. try:
  488. image_files = list(self._image_save_dir.glob("*.jpg"))
  489. if len(image_files) > self._image_max_count:
  490. # 按修改时间排序,删除最旧的
  491. image_files.sort(key=lambda x: x.stat().st_mtime)
  492. to_delete = image_files[:len(image_files) - self._image_max_count]
  493. for f in to_delete:
  494. f.unlink()
  495. logger.info(f"已清理 {len(to_delete)} 张旧检测图片")
  496. except Exception as e:
  497. logger.error(f"清理旧图片失败: {e}")
  498. def _save_detection_image(self, frame: np.ndarray, detections: List[DetectedObject]):
  499. """
  500. 保存带有检测标记的图片(只标记达到置信度阈值的人)
  501. Args:
  502. frame: 原始图像
  503. detections: 检测结果列表
  504. """
  505. if not self._save_image_enabled or not detections:
  506. return
  507. # 检查保存间隔
  508. current_time = time.time()
  509. if current_time - self._last_save_time < self._save_interval:
  510. return
  511. try:
  512. # 复制图像避免修改原图
  513. marked_frame = frame.copy()
  514. # 置信度阈值(人员检测用更高阈值)
  515. person_threshold = self.config.get('person_threshold', 0.8)
  516. # 只标记达到阈值的人
  517. person_count = 0
  518. for det in detections:
  519. # 只处理人且达到阈值
  520. is_person = det.class_name in ['person']
  521. if not is_person:
  522. continue
  523. # 未达阈值的不标记
  524. if det.confidence < person_threshold:
  525. continue
  526. x, y, w, h = det.bbox
  527. # 绘制边界框(绿色)
  528. cv2.rectangle(marked_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  529. # 绘制序号标签
  530. label = f"person_{person_count}"
  531. person_count += 1
  532. (label_w, label_h), baseline = cv2.getTextSize(
  533. label, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2
  534. )
  535. cv2.rectangle(
  536. marked_frame,
  537. (x, y - label_h - 8),
  538. (x + label_w, y),
  539. (0, 255, 0),
  540. -1
  541. )
  542. # 绘制标签文字(黑色)
  543. cv2.putText(
  544. marked_frame, label,
  545. (x, y - 4),
  546. cv2.FONT_HERSHEY_SIMPLEX, 0.8,
  547. (0, 0, 0), 2
  548. )
  549. # 无有效目标则不保存
  550. if person_count == 0:
  551. return
  552. # 生成文件名(时间戳+有效人数)
  553. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
  554. filename = f"panorama_{timestamp}_n{person_count}.png"
  555. filepath = self._image_save_dir / filename
  556. # 保存图片(PNG无损格式,不压缩)
  557. cv2.imwrite(str(filepath), marked_frame)
  558. self._last_save_time = current_time
  559. logger.info(f"[全景] 已保存检测图片: {filepath},有效人数 {person_count} (阈值={person_threshold})")
  560. # 定期清理旧图片
  561. self._cleanup_old_images()
  562. except Exception as e:
  563. logger.error(f"[全景] 保存检测图片失败: {e}")
  564. def _letterbox(self, image, size=(640, 640)):
  565. """Letterbox 预处理"""
  566. h0, w0 = image.shape[:2]
  567. ih, iw = size
  568. scale = min(iw / w0, ih / h0)
  569. new_w, new_h = int(w0 * scale), int(h0 * scale)
  570. pad_w = (iw - new_w) // 2
  571. pad_h = (ih - new_h) // 2
  572. resized = cv2.resize(image, (new_w, new_h))
  573. canvas = np.full((ih, iw, 3), 114, dtype=np.uint8)
  574. canvas[pad_h:pad_h+new_h, pad_w:pad_w+new_w] = resized
  575. return canvas, scale, pad_w, pad_h, h0, w0
  576. @staticmethod
  577. def _make_grid(h: int, w: int):
  578. """生成特征图网格坐标"""
  579. yv, xv = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
  580. return np.stack([xv, yv], axis=-1).reshape(-1, 2)
  581. @staticmethod
  582. def _pseudo_person_confidence(bboxes: np.ndarray, orig_h: int, orig_w: int) -> np.ndarray:
  583. """
  584. 当 RKNN 模型 cls 输出恒定时,根据 bbox 形状生成伪置信度。
  585. bboxes: (N, 4) [x1, y1, x2, y2] 原始图像坐标
  586. """
  587. x1, y1, x2, y2 = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
  588. w = np.maximum(1.0, x2 - x1)
  589. h = np.maximum(1.0, y2 - y1)
  590. aspect = h / w
  591. # 人体宽高比通常在 1.5 ~ 4.0 之间,以 2.5 为最佳
  592. aspect_score = np.exp(-0.5 * ((aspect - 2.5) / 1.0) ** 2)
  593. # 面积占画面比例,过大/过小都降权
  594. area = w * h
  595. img_area = orig_w * orig_h
  596. area_ratio = area / img_area
  597. size_score = np.clip(area_ratio * 80, 0.0, 1.0) # 占画面 1.25% 以上得满分
  598. # 综合伪置信度,范围 0.55 ~ 0.95
  599. conf = 0.55 + 0.30 * aspect_score + 0.10 * size_score
  600. return conf
  601. def _decode_yolo11_outputs(self, outputs: list, canvas_size: tuple,
  602. scale: float, pad_w: int, pad_h: int,
  603. orig_h: int, orig_w: int,
  604. conf_threshold: float = 0.5,
  605. iou_threshold: float = 0.45) -> list:
  606. """
  607. 解码 YOLO11 RKNN 多输出格式 (DFL bbox + cls + mask,每尺度 3 个输出)
  608. outputs: [bbox_80x80, cls_80x80, mask_80x80, bbox_40x40, cls_40x40, ...]
  609. 返回: [[x1, y1, x2, y2, score, class_id], ...] (原始图像坐标)
  610. """
  611. strides = [8, 16, 32]
  612. reg_max = 16
  613. dets = []
  614. # 记录 cls 输出是否异常(常量),用于后续 fallback
  615. cls_constant = True
  616. for scale_idx, stride in enumerate(strides):
  617. bbox_out = outputs[scale_idx * 3]
  618. cls_out = outputs[scale_idx * 3 + 1]
  619. # 检测 cls 是否为常量(量化/导出异常导致)
  620. if np.ptp(cls_out) > 1e-4:
  621. cls_constant = False
  622. _, _, h, w = bbox_out.shape
  623. # (64, H, W) -> (H*W, 4, 16)
  624. bbox = bbox_out[0].transpose(1, 2, 0).reshape(h * w, 4, reg_max)
  625. # (80, H, W) -> (H*W, 80)
  626. cls = cls_out[0].transpose(1, 2, 0).reshape(h * w, 80)
  627. # DFL 解码
  628. prob = np.exp(bbox - np.max(bbox, axis=-1, keepdims=True))
  629. prob = prob / np.sum(prob, axis=-1, keepdims=True)
  630. bins = np.arange(reg_max).reshape(1, 1, reg_max)
  631. decoded = np.sum(prob * bins, axis=-1) # (H*W, 4)
  632. # 网格中心
  633. grid = self._make_grid(h, w) + 0.5 # (H*W, 2)
  634. l, t, r, b = decoded[:, 0], decoded[:, 1], decoded[:, 2], decoded[:, 3]
  635. x1 = (grid[:, 0] - l) * stride
  636. y1 = (grid[:, 1] - t) * stride
  637. x2 = (grid[:, 0] + r) * stride
  638. y2 = (grid[:, 1] + b) * stride
  639. # cls sigmoid
  640. cls = 1.0 / (1.0 + np.exp(-cls))
  641. scores = np.max(cls, axis=1)
  642. labels = np.argmax(cls, axis=1)
  643. for i in range(len(scores)):
  644. if scores[i] < conf_threshold:
  645. continue
  646. dets.append([x1[i], y1[i], x2[i], y2[i], scores[i], labels[i]])
  647. if not dets:
  648. return []
  649. dets = np.array(dets)
  650. # 从 canvas(640x640) 坐标映射回原始图像坐标:去 padding -> 除以 scale
  651. dets[:, [0, 2]] = (dets[:, [0, 2]] - pad_w) / scale
  652. dets[:, [1, 3]] = (dets[:, [1, 3]] - pad_h) / scale
  653. # clip
  654. dets[:, [0, 2]] = np.clip(dets[:, [0, 2]], 0, orig_w)
  655. dets[:, [1, 3]] = np.clip(dets[:, [1, 3]], 0, orig_h)
  656. # 若 cls 输出异常常量,用伪置信度替代,帮助 NMS 和后续过滤
  657. if cls_constant:
  658. pseudo_scores = self._pseudo_person_confidence(dets[:, :4], orig_h, orig_w)
  659. dets[:, 4] = pseudo_scores
  660. dets[:, 5] = 0 # 强制为 person 类别
  661. # NMS
  662. x1, y1, x2, y2 = dets[:, 0], dets[:, 1], dets[:, 2], dets[:, 3]
  663. scores = dets[:, 4]
  664. areas = (x2 - x1) * (y2 - y1)
  665. order = scores.argsort()[::-1]
  666. keep = []
  667. while order.size > 0:
  668. i = order[0]
  669. keep.append(i)
  670. xx1 = np.maximum(x1[i], x1[order[1:]])
  671. yy1 = np.maximum(y1[i], y1[order[1:]])
  672. xx2 = np.minimum(x2[i], x2[order[1:]])
  673. yy2 = np.minimum(y2[i], y2[order[1:]])
  674. w = np.maximum(0.0, xx2 - xx1)
  675. h = np.maximum(0.0, yy2 - yy1)
  676. inter = w * h
  677. iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-6)
  678. inds = np.where(iou <= iou_threshold)[0]
  679. order = order[inds + 1]
  680. return dets[keep].tolist()
  681. def _detect_rknn(self, frame: np.ndarray) -> List[DetectedObject]:
  682. """使用 RKNN/ONNX 模型检测"""
  683. results = []
  684. h0, w0 = frame.shape[:2]
  685. # 宽幅图(宽高比>2.5)使用分区域检测,避免letterbox后人太小
  686. if w0 / h0 > 2.5:
  687. return self._detect_rknn_tiled(frame)
  688. try:
  689. conf_threshold = self.config['confidence_threshold']
  690. class_map = self.config.get('class_map', {0: 'person'})
  691. # -------------------------------------------------------
  692. # end2end 模型(内置NMS):letterbox + NHWC 预处理
  693. # 输出格式 (N, max_det, 6) = (x1,y1,x2,y2,conf,cls) 在 letterbox 空间
  694. # -------------------------------------------------------
  695. if self.is_end2end:
  696. canvas, scale, pad_w, pad_h, h0, w0 = self._letterbox(frame)
  697. img = canvas[..., ::-1].astype(np.float32) / 255.0
  698. blob = img[None, ...] # NHWC
  699. if hasattr(self, 'rknn'):
  700. outputs = self.rknn.inference(inputs=[blob])
  701. else:
  702. # ONNX 通常期望 NCHW,需转置
  703. nchw = blob.transpose(0, 3, 1, 2)
  704. outputs = self.session.run(None, {self.input_name: nchw})
  705. output = outputs[0]
  706. if len(output.shape) == 3:
  707. output = output[0]
  708. for i in range(output.shape[0]):
  709. x1_lb, y1_lb, x2_lb, y2_lb, conf, cls_id = output[i]
  710. if conf < conf_threshold:
  711. continue
  712. cls_name = class_map.get(int(cls_id), str(int(cls_id)))
  713. if cls_name not in self.config['target_classes']:
  714. continue
  715. # 从 letterbox 空间映射回原图
  716. x1 = int((x1_lb - pad_w) / scale)
  717. y1 = int((y1_lb - pad_h) / scale)
  718. x2 = int((x2_lb - pad_w) / scale)
  719. y2 = int((y2_lb - pad_h) / scale)
  720. x1 = max(0, min(w0, x1))
  721. y1 = max(0, min(h0, y1))
  722. x2 = max(0, min(w0, x2))
  723. y2 = max(0, min(h0, y2))
  724. if x2 - x1 < 10 or y2 - y1 < 10:
  725. continue
  726. results.append(DetectedObject(
  727. class_name=cls_name,
  728. confidence=float(conf),
  729. bbox=(x1, y1, x2 - x1, y2 - y1),
  730. center=((x1 + x2) // 2, (y1 + y2) // 2)
  731. ))
  732. return results
  733. # -------------------------------------------------------
  734. # 非 end2end 模型:letterbox + NHWC 预处理
  735. # -------------------------------------------------------
  736. canvas, scale, pad_w, pad_h, h0, w0 = self._letterbox(frame)
  737. if hasattr(self, 'rknn'):
  738. # RKNN
  739. img = canvas[..., ::-1].astype(np.float32) / 255.0
  740. blob = img[None, ...]
  741. outputs = self.rknn.inference(inputs=[blob])
  742. else:
  743. # ONNX
  744. img = canvas[..., ::-1].astype(np.float32) / 255.0
  745. img = img.transpose(2, 0, 1)
  746. blob = img[None, ...]
  747. outputs = self.session.run(None, {self.input_name: blob})
  748. # 根据输出数量判断格式:YOLO11 DFL 为 9 个输出(3 scales x 3 branches)
  749. if len(outputs) == 9:
  750. dets = self._decode_yolo11_outputs(
  751. outputs, (640, 640), scale, pad_w, pad_h, h0, w0,
  752. conf_threshold=conf_threshold
  753. )
  754. for x1, y1, x2, y2, score, cls_id in dets:
  755. cls_name = class_map.get(int(cls_id), str(int(cls_id)))
  756. if cls_name not in self.config['target_classes']:
  757. continue
  758. if x2 - x1 < 10 or y2 - y1 < 10:
  759. continue
  760. obj = DetectedObject(
  761. class_name=cls_name,
  762. confidence=float(score),
  763. bbox=(int(x1), int(y1), int(x2 - x1), int(y2 - y1)),
  764. center=(int((x1 + x2) / 2), int((y1 + y2) / 2))
  765. )
  766. results.append(obj)
  767. else:
  768. # 标准 (84, 8400) 格式(ONNX 或新 RKNN)
  769. output = outputs[0]
  770. if len(output.shape) == 3:
  771. output = output[0]
  772. num_boxes = output.shape[1]
  773. candidates = []
  774. for i in range(num_boxes):
  775. x_center = float(output[0, i])
  776. y_center = float(output[1, i])
  777. width = float(output[2, i])
  778. height = float(output[3, i])
  779. class_probs = output[4:, i]
  780. best_class = int(np.argmax(class_probs))
  781. confidence = float(class_probs[best_class])
  782. if confidence < conf_threshold:
  783. continue
  784. x1 = int(((x_center - width / 2) - pad_w) / scale)
  785. y1 = int(((y_center - height / 2) - pad_h) / scale)
  786. x2 = int(((x_center + width / 2) - pad_w) / scale)
  787. y2 = int(((y_center + height / 2) - pad_h) / scale)
  788. x1 = max(0, min(w0, x1))
  789. y1 = max(0, min(h0, y1))
  790. x2 = max(0, min(w0, x2))
  791. y2 = max(0, min(h0, y2))
  792. if x2 - x1 < 10 or y2 - y1 < 10:
  793. continue
  794. cls_name = class_map.get(best_class, str(best_class))
  795. if cls_name not in self.config['target_classes']:
  796. continue
  797. obj = DetectedObject(
  798. class_name=cls_name,
  799. confidence=confidence,
  800. bbox=(x1, y1, x2 - x1, y2 - y1),
  801. center=((x1 + x2) // 2, (y1 + y2) // 2)
  802. )
  803. candidates.append(obj)
  804. results = nms(candidates, iou_threshold=0.45)
  805. except Exception as e:
  806. logger.error(f"RKNN/ONNX 检测错误: {e}")
  807. import traceback
  808. logger.error(traceback.format_exc())
  809. return results
  810. def _detect_rknn_tiled(self, frame: np.ndarray) -> List[DetectedObject]:
  811. """分区域检测 - 将宽幅全景图分成多个重叠区域分别检测,提高远处目标识别率"""
  812. results = []
  813. h0, w0 = frame.shape[:2]
  814. conf_threshold = self.config['confidence_threshold']
  815. class_map = self.config.get('class_map', {0: 'person'})
  816. # 分3个重叠区域
  817. overlap = int(h0 * 0.2)
  818. regions = [
  819. (0, w0 // 3 + overlap),
  820. (w0 // 3 - overlap // 2, 2 * w0 // 3 + overlap // 2),
  821. (2 * w0 // 3 - overlap, w0),
  822. ]
  823. seen_centers = []
  824. for x_start, x_end in regions:
  825. crop = frame[:, x_start:x_end]
  826. ch, cw = crop.shape[:2]
  827. # end2end 模型:resize + NCHW
  828. if self.is_end2end:
  829. img = cv2.resize(crop, (640, 640))
  830. img = img.astype(np.float32) / 255.0
  831. if hasattr(self, 'rknn'):
  832. outputs = self.rknn.inference(inputs=[img.transpose(2, 0, 1)[None, ...]])
  833. else:
  834. outputs = self.session.run(None, {self.input_name: img.transpose(2, 0, 1)[None, ...]})
  835. output = outputs[0]
  836. if len(output.shape) == 3:
  837. output = output[0]
  838. dets = []
  839. for i in range(output.shape[0]):
  840. x1, y1, x2, y2, conf, cls_id = output[i]
  841. if conf < conf_threshold:
  842. continue
  843. cls_name = class_map.get(int(cls_id), str(int(cls_id)))
  844. if cls_name not in self.config['target_classes']:
  845. continue
  846. _x1 = int(x1 * cw / 640)
  847. _y1 = int(y1 * ch / 640)
  848. _x2 = int(x2 * cw / 640)
  849. _y2 = int(y2 * ch / 640)
  850. dets.append([_x1, _y1, _x2, _y2, float(conf), int(cls_id)])
  851. else:
  852. canvas, scale, pad_w, pad_h, ch, cw = self._letterbox(crop)
  853. if hasattr(self, 'rknn'):
  854. img = canvas[..., ::-1].astype(np.float32) / 255.0
  855. outputs = self.rknn.inference(inputs=[img[None, ...]])
  856. else:
  857. img = canvas[..., ::-1].astype(np.float32) / 255.0
  858. img = img.transpose(2, 0, 1)
  859. outputs = self.session.run(None, {self.input_name: img[None, ...]})
  860. if len(outputs) == 9:
  861. dets = self._decode_yolo11_outputs(
  862. outputs, (640, 640), scale, pad_w, pad_h, ch, cw,
  863. conf_threshold=conf_threshold
  864. )
  865. else:
  866. # 标准 (84, 8400) 格式
  867. output = outputs[0]
  868. if len(output.shape) == 3:
  869. output = output[0]
  870. dets = []
  871. for i in range(output.shape[1]):
  872. class_probs = output[4:, i]
  873. best_class = int(np.argmax(class_probs))
  874. confidence = float(class_probs[best_class])
  875. if confidence < conf_threshold:
  876. continue
  877. x1 = output[0, i] - output[2, i] / 2
  878. y1 = output[1, i] - output[3, i] / 2
  879. x2 = output[0, i] + output[2, i] / 2
  880. y2 = output[1, i] + output[3, i] / 2
  881. dets.append([x1, y1, x2, y2, confidence, best_class])
  882. # 从 canvas 坐标映射回 crop 坐标
  883. dets = np.array(dets) if dets else np.zeros((0, 6))
  884. dets[:, [0, 2]] = (dets[:, [0, 2]] - pad_w) / scale
  885. dets[:, [1, 3]] = (dets[:, [1, 3]] - pad_h) / scale
  886. dets = dets.tolist()
  887. for x1, y1, x2, y2, confidence, best_class in dets:
  888. cls_name = class_map.get(int(best_class), str(int(best_class)))
  889. if cls_name not in self.config['target_classes']:
  890. continue
  891. # 转换到原图坐标(加上区域偏移)
  892. x1 = int(x1) + x_start
  893. y1 = int(y1)
  894. x2 = int(x2) + x_start
  895. y2 = int(y2)
  896. x1 = max(0, min(w0, x1))
  897. y1 = max(0, min(h0, y1))
  898. x2 = max(0, min(w0, x2))
  899. y2 = max(0, min(h0, y2))
  900. if x2 - x1 < 10 or y2 - y1 < 10:
  901. continue
  902. # 去重:同一目标可能被相邻区域重复检测
  903. cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
  904. if any(abs(cx - sx) < 50 and abs(cy - sy) < 50 for sx, sy in seen_centers):
  905. continue
  906. seen_centers.append((cx, cy))
  907. obj = DetectedObject(
  908. class_name=cls_name,
  909. confidence=float(confidence),
  910. bbox=(x1, y1, x2 - x1, y2 - y1),
  911. center=(cx, cy)
  912. )
  913. results.append(obj)
  914. return results
  915. def detect(self, frame: np.ndarray) -> List[DetectedObject]:
  916. """检测物体返回所有类别结果"""
  917. if frame is None:
  918. return []
  919. if hasattr(self, 'rknn') and self.rknn is not None:
  920. results = self._detect_rknn(frame)
  921. if results:
  922. self._log_detections("RKNN", results, frame)
  923. self._save_detection_image(frame, results)
  924. return results
  925. elif hasattr(self, 'session') and self.session is not None:
  926. results = self._detect_rknn(frame)
  927. if results:
  928. self._log_detections("ONNX", results, frame)
  929. self._save_detection_image(frame, results)
  930. return results
  931. elif self.model is not None:
  932. results = self._detect_yolo(frame)
  933. if results:
  934. self._log_detections("YOLO", results, frame)
  935. self._save_detection_image(frame, results)
  936. return results
  937. else:
  938. logger.error("[YOLO] 没有可用的检测模型")
  939. return []
  940. def _log_detections(self, model_type: str, results: List[DetectedObject], frame: np.ndarray):
  941. if not results:
  942. return
  943. class_counts = {}
  944. for r in results:
  945. class_counts[r.class_name] = class_counts.get(r.class_name, 0) + 1
  946. h, w = frame.shape[:2]
  947. logger.info(f"[YOLO] {model_type}: {len(results)}个目标 {class_counts} (帧尺寸={w}x{h})")
  948. def _detect_yolo(self, frame: np.ndarray) -> List[DetectedObject]:
  949. """使用 YOLO 模型检测"""
  950. results = []
  951. try:
  952. detections = self.model(
  953. frame,
  954. device=self.device,
  955. verbose=False,
  956. conf=self.config['confidence_threshold']
  957. )
  958. for det in detections:
  959. boxes = det.boxes
  960. if boxes is None:
  961. continue
  962. for i in range(len(boxes)):
  963. cls_id = int(boxes.cls[i])
  964. cls_name = det.names[cls_id]
  965. if cls_name not in self.config['target_classes']:
  966. continue
  967. conf = float(boxes.conf[i])
  968. xyxy = boxes.xyxy[i].cpu().numpy()
  969. x1, y1, x2, y2 = map(int, xyxy)
  970. width = x2 - x1
  971. height = y2 - y1
  972. if width < 10 or height < 10:
  973. continue
  974. center_x = x1 + width // 2
  975. center_y = y1 + height // 2
  976. obj = DetectedObject(
  977. class_name=cls_name,
  978. confidence=conf,
  979. bbox=(x1, y1, width, height),
  980. center=(center_x, center_y)
  981. )
  982. results.append(obj)
  983. except Exception as e:
  984. logger.error(f"YOLO11检测错误: {e}")
  985. return results
  986. def detect_with_keypoints(self, frame: np.ndarray) -> List[DetectedObject]:
  987. """
  988. 使用YOLO11-pose检测人体并返回关键点
  989. Args:
  990. frame: 输入图像
  991. Returns:
  992. 带关键点的检测结果列表
  993. """
  994. return self.detect(frame)
  995. def detect_persons(self, frame: np.ndarray) -> List[DetectedObject]:
  996. """检测人体(支持中英文类别名)"""
  997. all_detections = self.detect(frame)
  998. person_classes = {'person', '人'}
  999. return [obj for obj in all_detections if obj.class_name in person_classes]
  1000. def release(self):
  1001. """释放模型资源"""
  1002. if hasattr(self, 'rknn') and self.rknn:
  1003. self.rknn.release()
  1004. self.rknn = None
  1005. self.model = None
  1006. self.session = None