Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/Driving_Accident_Video_Recognition/config.py
Original file line number Diff line number Diff line change
@@ -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"
Binary file not shown.
Binary file not shown.
121 changes: 121 additions & 0 deletions src/Driving_Accident_Video_Recognition/core/detector.py
Original file line number Diff line number Diff line change
@@ -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"]
46 changes: 46 additions & 0 deletions src/Driving_Accident_Video_Recognition/core/process.py
Original file line number Diff line number Diff line change
@@ -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"]
35 changes: 35 additions & 0 deletions src/Driving_Accident_Video_Recognition/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
主程序入口:整合所有模块,启动驾驶事故检测工具
"""
import sys
import os

# 关键:将当前脚本所在的目录(code目录)加入Python模块搜索路径
# 确保Python能找到core、utils等子模块
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

# 现在可以正常导入模块了
from config import REQUIRED_PACKAGES, PYPI_MIRROR
from utils.dependencies import install_dependencies
from core.detector import AccidentDetector

def main():
"""主函数:执行依赖安装 → 初始化检测器 → 启动检测"""
try:
print("🚀 启动驾驶事故视频识别工具...")
# 第一步:自动安装依赖
install_dependencies(REQUIRED_PACKAGES, PYPI_MIRROR)
# 第二步:初始化检测器
detector = AccidentDetector()
# 第三步:启动检测
detector.run_detection()
except KeyboardInterrupt:
print("\n🛑 用户强制中断程序")
except Exception as e:
print(f"\n❌ 程序运行出错:{e}")
finally:
print("👋 程序正常退出")

if __name__ == "__main__":
main()
Loading