基于深度学习的疲劳驾驶检测系统

基于深度学习的疲劳驾驶检测系统利用深度学习算法对驾驶员的眼睛和脸部表情等特征进行实时监测和分析,以识别出可能存在的疲劳驾驶行为。系统通过摄像头实时捕捉驾驶员的面部信息,并通过深度学习模型进行特征提取和分析,从而及时发出警告或采取相应措施,确保驾驶安全。

数据集

数据集来源

效果展示

在这里插入图片描述

训练代码

metrics_results = {}
    for exp_id, config in experiments.items():
        try:
            logging.info(f"🚀 开始实验 {exp_id}")
            model = YOLO(config["model"], verbose=False)
            device = "cuda" if torch.cuda.is_available() else "cpu"
            save_dir = os.path.join("results", f"exp_{exp_id}")
            os.makedirs(save_dir, exist_ok=True)
            logging.info(f"加载数据集: {data_yaml_path}")
            logging.info(f"使用设备: {device}")
            logging.info(f"开始训练模型: {config['model']}")

            results = model.train(
                data=data_yaml_path,
                epochs=config["epochs"],
                batch=config["batch"],
                imgsz=config["imgsz"],
                augment=config["augment"], 
                device=device,
                patience=10,
                save=True,
                project="results",
                name=f"exp_{exp_id}"
            )

测试代码

def process_images_in_folder(folder_path):
    image_extensions = ['.jpg', '.jpeg', '.png']
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if any(file.lower().endswith(ext) for ext in image_extensions):
                image_path = os.path.join(root, file)
                print(f"Processing image: {image_path}")
                annotated_images, detection_results, inference_time = predict_and_visualize(image_path)

                print(f"Inference time: {inference_time:.2f} seconds")
                print("Detection results:")
                for result in detection_results:
                    print(f"Class: {result['class']}, Score: {result['score']:.2f}, Box: {result['box']}")

                yield image_path, annotated_images


def visualize_image(image_path, annotated_images):
    original_image = cv2.imread(image_path)
    original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

    ax1.imshow(original_image)
    ax1.set_title("Original Image")
    ax1.axis('off')

    annotated_image = annotated_images[0]
    annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
    ax2.imshow(annotated_image)
    ax2.set_title("Annotated Image")
    ax2.axis('off')

    plt.tight_layout()
    plt.show()


def process_video(video_path, output_path):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"Error: Could not open video {video_path}")
        return

    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')

    out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))

    frame_count = 0
    total_time = 0.0
    paused = False

    while cap.isOpened():
        if not paused:
            ret, frame = cap.read()
            if not ret:
                break

            frame_count += 1
            frame_path = f"temp_frame_{frame_count}.jpg"
            cv2.imwrite(frame_path, frame)

            annotated_images, _, inference_time = predict_and_visualize(frame_path)
            total_time += inference_time

            if annotated_images:
                annotated_frame = annotated_images[0]
                out.write(annotated_frame)
                cv2.imshow("Annotated Frame", annotated_frame)

            os.remove(frame_path)
            print(f"Processed frame {frame_count}, Inference time: {inference_time:.2f} seconds")

        key = cv2.waitKey(1) & 0xFF
        if key == ord('q'):
            break
        elif key == ord('p'):
            paused = True
            print("Video paused. Press 'c' to continue.")
        elif key == ord('c') and paused:
            paused = False
            print("Video resumed.")

    cap.release()
    out.release()
    cv2.destroyAllWindows()

    avg_fps = frame_count / total_time if total_time > 0 else 0
    print(f"Processed {frame_count} frames, Total time: {total_time:.2f} seconds, Average FPS: {avg_fps:.2f}")


结论

  1. 深度学习技术在疲劳驾驶检测领域具有很大潜力,可以实现自动监测驾驶员的疲劳程度。

  2. 经过一定的训练和优化,深度学习系统在疲劳驾驶检测方面可以取得较高的准确率和稳定性。

  3. 深度学习疲劳驾驶检测系统有望在实际道路驾驶场景中发挥重要作用,提高交通安全水平。

  4. 未来可能需要进一步研究和改进深度学习疲劳驾驶检测系统,以提高其在不同条件下的适用性和鲁棒性。

博主联系

微信公号搜索 HJF数据分析及安全关注后, 回复关键字联系方式获取联系方式。

更多推荐