1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
| import zmq import cv2 import numpy as np import signal import os import time from datetime import datetime from ultralytics import YOLO from multiprocessing import Process, Queue, Event from queue import Empty, Full
LISTEN_PORT = 5555 MODEL_PATH = r"runs/detect/train-8/weights/best.pt" CONF_THRESH = 0.6 IOU_THRESH = 0.5 INFER_QUEUE_MAX = 6 ZMQ_RECV_HWM = 6 ZMQ_RECV_TIMEOUT = 5 WIN_NAME = "YOLO Pedestrian Detection" YOLO_VERBOSE_PRINT = False
SAVE_VIDEO = True VIDEO_QUEUE_MAX = 12 VIDEO_FPS = 15 VIDEO_DIR = "./runs/detect/ped_event_video" VIDEO_EXT = ".mp4" FOURCC = cv2.VideoWriter_fourcc(*"mp4v") EVENT_GAP_SEC = 1.5
SHOW_FPS = 30
SHOW_INTERVAL_MS = int(1000 / SHOW_FPS)
WAIT_PROC_TIMEOUT = 3.5 SHOW_ORIGIN_FRAME = False
def infer_process(in_q: Queue, out_q: Queue, exit_evt: Event): import signal signal.signal(signal.SIGINT, signal.SIG_IGN) try: model = YOLO(MODEL_PATH) print("[推理进程] YOLO模型加载完成", flush=True) except Exception as e: import traceback print("[推理进程] 模型加载失败!", flush=True) print(traceback.format_exc(), flush=True) return try: while not exit_evt.is_set(): try: frame = in_q.get(timeout=0.05) except Empty: continue try: res = model(frame, conf=CONF_THRESH, iou=IOU_THRESH, verbose=YOLO_VERBOSE_PRINT)[0] boxes = res.boxes.data.cpu().numpy() if res.boxes else np.empty((0,6)) try: out_q.put((frame, boxes), timeout=0.05) except Full: pass except Exception as e: import traceback print("[推理进程] YOLO推理发生致命错误:", flush=True) print(traceback.format_exc(), flush=True) raise e except KeyboardInterrupt: pass while True: try: out_q.get_nowait() except Empty: break import torch del model if torch.cuda.is_available(): torch.cuda.empty_cache() time.sleep(0.8) print("[推理进程] 退出", flush=True)
def video_writer_process(vid_q: Queue, exit_evt: Event): import signal signal.signal(signal.SIGINT, signal.SIG_IGN) os.makedirs(VIDEO_DIR, exist_ok=True) writer = None current_video_path = "" frame_size = None try: while not exit_evt.is_set(): try: msg = vid_q.get(timeout=0.1) except Empty: continue
msg_type = msg[0] if msg_type == "start": if writer is not None: writer.release() print(f"[录像进程] 上次事件文件已保存:{current_video_path}", flush=True) draw_frame, start_ts = msg[1], msg[2] h, w = draw_frame.shape[:2] frame_size = (w, h) file_name = f"ped_event_{start_ts}{VIDEO_EXT}" current_video_path = os.path.join(VIDEO_DIR, file_name) writer = cv2.VideoWriter(current_video_path, FOURCC, VIDEO_FPS, frame_size) print(f"[录像进程] 新行人事件开始,创建视频:{current_video_path}", flush=True) writer.write(draw_frame)
elif msg_type == "frame": draw_frame = msg[1] if writer is not None: writer.write(draw_frame)
elif msg_type == "end": if writer is not None: writer.release() print(f"[录像进程] 行人事件结束,文件保存完成:{current_video_path}", flush=True) writer = None current_video_path = "" except KeyboardInterrupt: pass if writer is not None: writer.release() print(f"[录像进程] 程序退出,收尾视频:{current_video_path}", flush=True) else: print("[录像进程] 退出", flush=True)
def main(): exit_event = Event() input_q = Queue(maxsize=INFER_QUEUE_MAX) output_q = Queue(maxsize=INFER_QUEUE_MAX) infer_proc = Process(target=infer_process, args=(input_q, output_q, exit_event), daemon=True) infer_proc.start() print(f"[主线] YOLO推理进程启动")
vid_queue = None vid_proc = None if SAVE_VIDEO: vid_queue = Queue(maxsize=VIDEO_QUEUE_MAX) vid_proc = Process(target=video_writer_process, args=(vid_queue, exit_event), daemon=True) vid_proc.start() print(f"[主线] 录像进程启动,每个行人事件将独立保存至 {VIDEO_DIR}")
def safe_put_end(q: Queue): try: q.put_nowait(("end",)) except Full: try: q.get_nowait() q.put_nowait(("end",)) except Empty: pass def stop_recording(vid_proc): if vid_proc and vid_proc.is_alive(): safe_put_end(vid_queue) time.sleep(0.2)
is_recording = False no_ped_start_time = None
def sigint_handler(sig, frame): print("\n收到Ctrl+C,准备退出,等待资源收尾...", flush=True) while True: try: input_q.get_nowait() except Empty: break exit_event.set() signal.signal(signal.SIGINT, sigint_handler)
ctx = zmq.Context() pull_sock = ctx.socket(zmq.PULL) pull_sock.setsockopt(zmq.RCVHWM, ZMQ_RECV_HWM) pull_sock.setsockopt(zmq.RCVTIMEO, ZMQ_RECV_TIMEOUT) pull_sock.setsockopt(zmq.LINGER, 0) pull_sock.bind(f"tcp://0.0.0.0:{LISTEN_PORT}")
cv2.namedWindow(WIN_NAME, cv2.WINDOW_AUTOSIZE) print(f"[主线] 检测服务启动,监听端口 {LISTEN_PORT} | Ctrl+C / Q键退出")
zero_frame = np.zeros((480,640,3), dtype=np.uint8) last_draw = zero_frame last_show_time = time.time() try: while not exit_event.is_set(): frame = None try: jpg_bytes = pull_sock.recv() arr = np.frombuffer(jpg_bytes, np.uint8) frame = cv2.imdecode(arr, cv2.IMREAD_COLOR) except zmq.Again: pass
if frame is not None: try: input_q.put_nowait(frame) except Full: pass
draw = None has_ped = False
try: img, boxes = output_q.get_nowait() draw = img.copy() has_ped = len(boxes) > 0 for b in boxes: x1, y1, x2, y2 = map(int, b[:4]) conf, cls = b[4:] cv2.rectangle(draw, (x1,y1), (x2,y2), (0,255,0), 2) cv2.putText(draw, f"{conf:.2f}", (x1,y1-6), cv2.FONT_HERSHEY_SIMPLEX,0.45,(0,255,0),1) last_draw = draw except Empty: pass
draw = draw if draw is not None else last_draw show_current_frame = False now = time.time() if SHOW_ORIGIN_FRAME: if frame is not None: cv2.imshow(WIN_NAME, frame) if (now - last_show_time) * 1000 >= SHOW_INTERVAL_MS: if not SHOW_ORIGIN_FRAME: cv2.imshow(WIN_NAME, draw) last_show_time = now show_current_frame = True
key = cv2.waitKey(5) if key & 0xFF == ord("q"): while True: try: input_q.get_nowait() except Empty: break break
if not SAVE_VIDEO: continue if SHOW_ORIGIN_FRAME: continue if not show_current_frame: continue now_ts = datetime.now().strftime("%Y%m%d_%H%M%S") now_sec = time.time()
if has_ped: no_ped_start_time = None if not is_recording: try: vid_queue.put_nowait(("start", draw, now_ts)) except Full: pass is_recording = True else: try: vid_queue.put_nowait(("frame", draw)) except Full: pass else: if is_recording: if no_ped_start_time is None: no_ped_start_time = now_sec gap_duration = now_sec - no_ped_start_time if (gap_duration < EVENT_GAP_SEC): try: vid_queue.put_nowait(("frame", draw)) except Full: pass else: safe_put_end(vid_queue) is_recording = False no_ped_start_time = None
finally: stop_recording(vid_proc) exit_event.set() time.sleep(1.5)
print("[主线] 等待推理进程退出...", flush=True) if infer_proc.is_alive(): infer_proc.join(timeout=WAIT_PROC_TIMEOUT) if infer_proc.is_alive(): print("[警告] 推理进程超时未退出,强制终止", flush=True) infer_proc.terminate() infer_proc.join()
if vid_proc is not None and vid_proc.is_alive(): print("[主线] 等待录像进程退出...", flush=True) vid_proc.join(timeout=WAIT_PROC_TIMEOUT) if vid_proc.is_alive(): print("[警告] 录像进程超时未退出,强制终止", flush=True) vid_proc.terminate() vid_proc.join()
pull_sock.close() ctx.term() cv2.destroyAllWindows() print("[主线] 程序资源全部释放完毕")
if __name__ == "__main__": main()
|