From 3e4f04d3adbedca0ae2c0d056c155fee349c0a21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E5=87=AF?= <2684756428@qq.com> Date: Fri, 19 Dec 2025 21:51:33 +0800 Subject: [PATCH] Add files via upload --- .../config.py | 29 +++++ .../dependencies.py | 44 +++++++ .../detector.py | 121 ++++++++++++++++++ .../main.py | 55 ++++++++ .../process.py | 46 +++++++ 5 files changed, 295 insertions(+) create mode 100644 src/Driving_Accident_Video_Recognition/config.py create mode 100644 src/Driving_Accident_Video_Recognition/dependencies.py create mode 100644 src/Driving_Accident_Video_Recognition/detector.py create mode 100644 src/Driving_Accident_Video_Recognition/main.py create mode 100644 src/Driving_Accident_Video_Recognition/process.py diff --git a/src/Driving_Accident_Video_Recognition/config.py b/src/Driving_Accident_Video_Recognition/config.py new file mode 100644 index 0000000000..78f37f238b --- /dev/null +++ b/src/Driving_Accident_Video_Recognition/config.py @@ -0,0 +1,29 @@ +""" +全局配置文件:所有可配置参数集中管理,新手只需修改这里 +""" +# YOLOv8模型配置 +YOLO_MODEL_PATH = "yolov8n.pt" # 轻量化模型(自动下载) +CONFIDENCE_THRESHOLD = 0.5 # 目标检测置信度阈值(0-1) + +# 检测源配置 +DETECTION_SOURCE = 0 # 0=电脑摄像头,可改为视频路径如"test_accident.mp4" + +# 事故识别配置 +ACCIDENT_CLASSES = [0, 2, 7] # YOLOv8类别:0=人,2=汽车,7=卡车 +MIN_VEHICLE_COUNT = 2 # 至少2辆车判定为事故 +PERSON_VEHICLE_CONTACT = True # 行人和车辆同时出现判定为事故 + +# 帧处理优化配置(低配电脑推荐) +RESIZE_WIDTH = 640 +RESIZE_HEIGHT = 480 + +# 依赖包配置 +REQUIRED_PACKAGES = [ + "ultralytics>=8.0.0", + "opencv-python>=4.8.0", + "numpy>=1.24.0", + "torch>=2.0.0" +] + +# 清华镜像源(加速依赖下载) +PYPI_MIRROR = "https://pypi.tuna.tsinghua.edu.cn/simple" \ No newline at end of file diff --git a/src/Driving_Accident_Video_Recognition/dependencies.py b/src/Driving_Accident_Video_Recognition/dependencies.py new file mode 100644 index 0000000000..135016d98d --- /dev/null +++ b/src/Driving_Accident_Video_Recognition/dependencies.py @@ -0,0 +1,44 @@ +""" +依赖管理工具:自动检查并安装缺失的依赖包,包含容错逻辑 +""" +import sys +import subprocess + +def install_dependencies(packages, mirror): + """ + 自动安装依赖包 + :param packages: 依赖包列表(来自config.py) + :param mirror: PyPI镜像源(来自config.py) + """ + for package in packages: + try: + # 提取包名(去掉版本号) + package_name = package.split('>=')[0] + # 检查包是否已安装 + if package_name == "ultralytics": + import ultralytics + elif package_name == "opencv-python": + import cv2 + elif package_name == "numpy": + import numpy + elif package_name == "torch": + import torch + print(f"✅ 依赖包 {package_name} 已安装") + except ImportError: + print(f"⚠️ 缺少依赖包 {package_name},正在自动安装...") + try: + # 使用镜像源安装,设置超时 + subprocess.check_call( + [sys.executable, "-m", "pip", "install", "-i", mirror, package], + timeout=300 # 5分钟超时 + ) + print(f"✅ 依赖包 {package_name} 安装成功") + except subprocess.TimeoutExpired: + print(f"❌ 安装 {package_name} 超时,尝试直接安装...") + subprocess.check_call([sys.executable, "-m", "pip", "install", package]) + except Exception as e: + print(f"❌ 安装 {package_name} 失败:{e}") + sys.exit(1) + +# 供外部导入的函数 +__all__ = ["install_dependencies"] \ No newline at end of file diff --git a/src/Driving_Accident_Video_Recognition/detector.py b/src/Driving_Accident_Video_Recognition/detector.py new file mode 100644 index 0000000000..4155840ab8 --- /dev/null +++ b/src/Driving_Accident_Video_Recognition/detector.py @@ -0,0 +1,121 @@ +""" +事故检测器核心类:负责模型加载、检测流程执行 +""" +import sys +import cv2 +from ultralytics import YOLO +from config import ( + YOLO_MODEL_PATH, CONFIDENCE_THRESHOLD, ACCIDENT_CLASSES, + MIN_VEHICLE_COUNT, PERSON_VEHICLE_CONTACT, + RESIZE_WIDTH, RESIZE_HEIGHT, DETECTION_SOURCE +) +from core.process import process_box_coords, draw_annotations + +class AccidentDetector: + def __init__(self): + """初始化检测器,加载YOLOv8模型""" + self.model = None + self.accident_detected = False + self._load_model() + + def _load_model(self): + """私有方法:加载模型,包含重试逻辑""" + try: + print("🔄 正在加载YOLOv8模型(首次运行会自动下载)...") + self.model = YOLO(YOLO_MODEL_PATH) + print("✅ YOLOv8模型加载成功") + except Exception as e: + print(f"❌ 模型加载失败:{e}") + # 重试加载模型 + try: + print("🔄 尝试重新下载模型...") + self.model = YOLO("yolov8n.pt") + print("✅ 模型重新加载成功") + except Exception as e2: + print(f"❌ 模型重新加载失败:{e2}") + sys.exit(1) + + def detect_frame(self, frame): + """处理单帧,返回标注后的帧和是否检测到事故""" + detected_objects = [] + try: + # 缩放帧提升速度 + frame_resized = cv2.resize(frame, (RESIZE_WIDTH, RESIZE_HEIGHT)) + # YOLOv8推理 + results = self.model(frame_resized, conf=CONFIDENCE_THRESHOLD) + + # 解析检测结果 + for r in results: + if hasattr(r, 'boxes') and r.boxes is not None: + for box in r.boxes: + if not hasattr(box, 'cls') or box.cls is None: + continue + cls_idx = int(box.cls[0]) + if cls_idx in ACCIDENT_CLASSES: + cls_name = self.model.names[cls_idx] + # 处理坐标 + scale_x = frame.shape[1] / RESIZE_WIDTH + scale_y = frame.shape[0] / RESIZE_HEIGHT + x1, y1, x2, y2 = process_box_coords(box, scale_x, scale_y) + detected_objects.append((cls_name, x1, y1, x2, y2)) + + # 判断事故 + person_count = sum(1 for obj in detected_objects if obj[0] == "person") + vehicle_count = sum(1 for obj in detected_objects if obj[0] in ["car", "truck"]) + is_accident = (vehicle_count >= MIN_VEHICLE_COUNT) or (person_count >= 1 and vehicle_count >= 1 and PERSON_VEHICLE_CONTACT) + self.accident_detected = is_accident + + # 绘制标注 + frame = draw_annotations(frame, detected_objects, is_accident) + + except Exception as e: + print(f"⚠️ 帧处理出现小错误:{e},继续运行...") + + return frame, self.accident_detected + + def run_detection(self): + """启动检测流程,包含完善的容错逻辑""" + # 多次尝试打开检测源 + cap = None + for i in range(3): + cap = cv2.VideoCapture(DETECTION_SOURCE) + if cap.isOpened(): + break + print(f"⚠️ 第{i+1}次打开检测源失败,重试中...") + cv2.waitKey(1000) + + if not cap or not cap.isOpened(): + print(f"❌ 无法打开检测源:{DETECTION_SOURCE}") + # 强制切换为摄像头 + print("🔄 强制切换为电脑摄像头...") + cap = cv2.VideoCapture(0) + if not cap.isOpened(): + print("❌ 摄像头也无法打开,请检查设备") + sys.exit(1) + + print("✅ 检测源打开成功,开始实时检测(按Q/ESC键退出)") + print("💡 提示:检测到2辆车或行人和车辆同时出现时,显示红色警告") + + # 逐帧处理 + while True: + ret, frame = cap.read() + if not ret: + print("🔚 视频/摄像头流结束") + break + + frame, _ = self.detect_frame(frame) + cv2.imshow("驾驶事故检测(按Q退出)", frame) + + # 退出逻辑 + key = cv2.waitKey(1) & 0xFF + if key == ord('q') or key == 27: + print("🛑 用户手动退出") + break + + # 释放资源 + cap.release() + cv2.destroyAllWindows() + print(f"\n📊 检测总结:是否检测到事故 → {'✅ 是' if self.accident_detected else '❌ 否'}") + +# 供外部导入的类 +__all__ = ["AccidentDetector"] \ No newline at end of file diff --git a/src/Driving_Accident_Video_Recognition/main.py b/src/Driving_Accident_Video_Recognition/main.py new file mode 100644 index 0000000000..eab5ee954a --- /dev/null +++ b/src/Driving_Accident_Video_Recognition/main.py @@ -0,0 +1,55 @@ +""" +主程序入口:整合所有模块,支持命令行参数控制 +""" +import sys +import os +import argparse # 新增:导入命令行解析模块 +# 关键:将当前脚本所在目录加入Python模块搜索路径 +current_dir = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(current_dir) + +from config import REQUIRED_PACKAGES, PYPI_MIRROR, SUPPORTED_LANGUAGES +from utils.dependencies import install_dependencies +from core.detector import AccidentDetector + +def parse_args(): + """新增:解析命令行参数""" + parser = argparse.ArgumentParser(description="驾驶事故视频识别工具") + # 检测源:-s/--source,支持摄像头(数字)或视频路径(字符串) + parser.add_argument( + "--source", "-s", + default=None, + help=f"检测源(0=摄像头,或视频路径如'test.mp4'),默认使用config.py配置" + ) + # 语言:-l/--lang,支持中文(zh)、英文(en) + parser.add_argument( + "--lang", "-l", + default="zh", + choices=SUPPORTED_LANGUAGES, + help=f"标注语言,支持{SUPPORTED_LANGUAGES},默认中文(zh)" + ) + return parser.parse_args() + +def main(): + """主函数:执行依赖安装 → 解析参数 → 启动检测""" + args = parse_args() # 新增:解析命令行参数 + try: + print("🚀 启动驾驶事故视频识别工具...") + # 第一步:自动安装依赖 + install_dependencies(REQUIRED_PACKAGES, PYPI_MIRROR) + # 第二步:初始化检测器 + detector = AccidentDetector() + # 第三步:启动检测(传递命令行参数:检测源、语言) + detector.run_detection( + source=args.source, # 优先使用命令行指定的检测源 + language=args.lang # 传递语言参数 + ) + except KeyboardInterrupt: + print("\n🛑 用户强制中断程序") + except Exception as e: + print(f"\n❌ 程序运行出错:{e}") + finally: + print("👋 程序正常退出") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/Driving_Accident_Video_Recognition/process.py b/src/Driving_Accident_Video_Recognition/process.py new file mode 100644 index 0000000000..87df8b1bbd --- /dev/null +++ b/src/Driving_Accident_Video_Recognition/process.py @@ -0,0 +1,46 @@ +""" +辅助处理工具:负责坐标转换、帧处理等通用逻辑 +""" +import numpy as np +import torch +import cv2 + +def process_box_coords(box, scale_x, scale_y): + """ + 安全处理YOLOv8检测框坐标,解决张量类型错误 + :param box: YOLOv8的检测框对象 + :param scale_x: 宽度缩放比例 + :param scale_y: 高度缩放比例 + :return: 转换后的坐标(x1, y1, x2, y2) + """ + # 兼容张量和numpy数组 + if isinstance(box.xyxy[0], torch.Tensor): + box_xyxy = box.xyxy[0].cpu().numpy() + else: + box_xyxy = np.array(box.xyxy[0]) + # 缩放坐标 + scaled_box = box_xyxy * [scale_x, scale_y, scale_x, scale_y] + # 转换为整数 + return map(int, scaled_box) + +def draw_annotations(frame, detected_objects, is_accident): + """ + 在帧上绘制检测标注和事故警告 + :param frame: 原始视频帧 + :param detected_objects: 检测到的目标列表 + :param is_accident: 是否检测到事故 + :return: 标注后的帧 + """ + # 绘制目标检测框 + for (cls_name, x1, y1, x2, y2) in detected_objects: + cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) + cv2.putText(frame, cls_name, (x1, y1 - 10), + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) + # 绘制事故警告 + if is_accident: + cv2.putText(frame, "⚠️ 检测到事故!", (50, 50), + cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3) + return frame + +# 供外部导入的函数 +__all__ = ["process_box_coords", "draw_annotations"] \ No newline at end of file