# Patch pour supporter la couche personnalisée "C3k" dans certains modèles YOLO
import ultralytics.nn.modules.block
ultralytics.nn.modules.block.C3k = ultralytics.nn.modules.block.C3 # fallback pour
couche inconnue
# Imports
from ultralytics import YOLO
import cv2
# Chargement du modèle
model = YOLO("Accident_model.pt")
# Chargement de la vidéo
video_path = "accident.mp4"
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise IOError(f"Erreur lors de l'ouverture de la vidéo : {video_path}")
# Configuration de la vidéo de sortie
output_path = "output_accident.mp4"
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
# Détection frame par frame
accident_detected = False
frame_count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame_count += 1
results = model(frame)
for result in results:
for box in result.boxes:
cls_id = int(box.cls[0])
conf = float(box.conf[0])
x1, y1, x2, y2 = map(int, box.xyxy[0])
if cls_id == 0 and conf > 0.5:
accident_detected = True
label = f"Accident ({conf:.2f})"
color = (0, 0, 255)
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
cv2.putText(frame, label, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
out.write(frame)
# Libération des ressources
cap.release()
out.release()
# Résultat
if accident_detected:
print("⚠️ Accident détecté. Résultat : output_accident.mp4")
else:
print("✅ Aucun accident détecté. Résultat : output_accident.mp4")