三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

基于YOLO+DeepSeek的疲劳驾驶检测系统 YOLO+DeepSeek+疲劳驾驶检测系统 Pytorch+SpringBoot+Flask+Vue

基于YOLO+DeepSeek的疲劳驾驶检测系统 YOLO+DeepSeek+疲劳驾驶检测系统 Pytorch+SpringBoot+Flask+Vue

YOLO+DeepSeek+疲劳驾驶检测系统

Pytorch+SpringBoot+Flask+Vue
配置好环境可直接使用,也可以自己加数据集训练,运行效果见图像及视频。
共4类标签[“睁眼”,“闭眼”,“打哈欠”,“未打哈欠”]

系统亮点:
多场景检测:支持单张图片、图片集、视频、实时摄像头等多种输入方式。
实时反馈:提供实时检测结果和详细分析报告,可导出 PDF。

高精度识别:基于改进 YOLOV5/8/11/12 结合 PyTorch 实现,疲劳驾分类检测准确率高,运行速度快。
AI智能分析:结合Deepseek/ Qwen 大模型智能分析,可生成详细检测建议。
直观UI界面:基于 Vue3 + Flask 前端展示,操作界面简洁清晰。

技术栈:
1、架构:B/S、MVC
2、系统环境:Windows、Mac
3、开发环境:IDEA、JDK1.8、Maven、Nodejs、Mysql、Python 3.9+
4、技术栈:Java、Mysql、Vue、spring boot、Mybatis、Element plus、Python、Flask、YOLOV5/8/11/12。

1

1

“基于YOLO+DeepSeek的疲劳驾驶检测系统”

SpringBoot后端接收请求->调用Python/YOLO进行推理->调用DeepSeek生成建议->Vue3前端展示结果

1. 核心架构设计

  • 前端: Vue 3 + Element Plus (负责界面、图片上传、结果展示、图表渲染)
  • 业务后端: Java SpringBoot (负责用户管理、记录存储、文件转发、调用AI接口)
  • 算法服务: Python Flask/FastAPI (负责加载YOLO模型,进行图像推理)
  • 大模型: DeepSeek API (负责根据YOLO的检测结果生成文本报告)

2. 数据库设计 (MySQL)

我们需要存储用户信息和检测记录。

CREATEDATABASEfatigue_detection_db;USEfatigue_detection_db;-- 用户表CREATETABLEusers(idINTPRIMARYKEYAUTO_INCREMENT,usernameVARCHAR(50)UNIQUENOTNULL,passwordVARCHAR(255)NOTNULL,roleVARCHAR(20)DEFAULT'USER',created_atTIMESTAMPDEFAULTCURRENT_TIMESTAMP);-- 检测记录表CREATETABLEdetection_logs(idINTPRIMARYKEYAUTO_INCREMENT,user_idINT,image_pathVARCHAR(255),result_labelVARCHAR(50),-- 例如:闭眼confidenceDECIMAL(5,4),-- 置信度inference_timeDECIMAL(10,4),-- 耗时ai_analysisTEXT,-- DeepSeek生成的分析报告created_atTIMESTAMPDEFAULTCURRENT_TIMESTAMP);

3. 算法服务层 (Python + YOLO)

这是系统的“眼睛”。使用ultralytics库加载训练好的疲劳驾驶模型。

安装依赖:
pip install fastapi uvicorn ultralytics opencv-python python-multipart

代码 (ai_service.py):

fromfastapiimportFastAPI,Query,UploadFile,FilefromultralyticsimportYOLOimportcv2importtimeimportosimportbase64 app=FastAPI()# 加载预训练模型 (假设你已经训练好并保存为 best.pt)# 标签映射: 0:睁眼,1:闭眼,2:打哈欠,3:未打哈欠model=YOLO("models/fatigue_best.pt")@app.post("/predict")asyncdefpredict(file:UploadFile=File(...),conf:float=0.5):start_time=time.time()# 保存上传的文件file_location=f"temp/{file.filename}"os.makedirs("temp",exist_ok=True)withopen(file_location,"wb+")asfile_object:file_object.write(file.file.read())# YOLO 推理results=model.predict(source=file_location,conf=conf,verbose=False)end_time=time.time()total_time=end_time-start_time response_data=[]forrinresults:forboxinr.boxes:cls_id=int(box.cls[0])cls_name=model.names[cls_id]score=float(box.conf[0])# 获取边界框坐标 [x1, y1, x2, y2]xyxy=box.xyxy[0].tolist()response_data.append({"label":cls_name,"confidence":round(score,4),"box":xyxy})# 清理临时文件os.remove(file_location)return{"detections":response_data,"time_cost":round(total_time,4),"image_url":f"/temp/{file.filename}"# 实际项目中应返回OSS地址}if__name__=="__main__":importuvicorn uvicorn.run(app,host="0.0.0.0",port=8000)

4. 业务后端 (Java SpringBoot)

这是系统的“大脑”。负责协调Python服务和DeepSeek API。

依赖 (pom.xml):
需要spring-boot-starter-web,lombok,okhttp(用于调用DeepSeek API)。

核心逻辑 (FatigueController.java):

@RestController@RequestMapping("/api/fatigue")@CrossOrigin(origins="*")publicclassFatigueController{@AutowiredprivateDetectionServicedetectionService;@PostMapping("/upload")publicResult<?>detect(@RequestParam("file")MultipartFilefile,@RequestParam(value="threshold",defaultValue="0.5")Doublethreshold){try{// 1. 调用 Python 服务获取检测结果Map<String,Object>yoloResult=detectionService.callPythonAI(file,threshold);// 2. 提取主要疲劳特征 (例如:只要有一个"闭眼"置信度>0.6,就判定为疲劳)StringmainLabel=extractMainLabel((List<Map>)yoloResult.get("detections"));// 3. 调用 DeepSeek 生成分析报告StringaiReport="";if("闭眼".equals(mainLabel)||"打哈欠".equals(mainLabel)){aiReport=detectionService.callDeepSeek(mainLabel);}else{aiReport="驾驶员状态良好,未检测到明显疲劳特征。";}// 4. 组装返回数据 (包含YOLO结果和AI报告)yoloResult.put("ai_report",aiReport);// 5. (可选) 保存到 MySQL 数据库// detectionService.saveRecord(...);returnResult.success(yoloResult);}catch(Exceptione){returnResult.error("检测失败:"+e.getMessage());}}// 辅助方法:调用 DeepSeek APIprivateStringcallDeepSeek(Stringlabel){Stringprompt="驾驶员被检测到行为:"+label+"。请作为交通安全专家,分析其风险(如PERCLOS标准),并给出3条具体的安全建议。要求语气专业、简练。";// 这里使用 OkHttp 发送 POST 请求到 https://api.deepseek.com/v1/chat/completions// 省略具体的 HTTP 请求代码,需填入你的 DeepSeek API Keyreturn"【DeepSeek分析】检测到"+label+",风险等级高。建议:1.立即停车休息;2.开启车窗通风...";}privateStringextractMainLabel(List<Map>detections){// 简单逻辑:返回置信度最高的标签if(detections.isEmpty())return"正常";return(String)detections.get(0).get("label");}}

5. 前端实现 (Vue 3)

这是系统的“脸面”。展示图片、绘制检测框、显示AI建议。

核心组件 (ImageDetect.vue):

<template><divclass="container"><!-- 左侧:上传与展示 --><divclass="canvas-area"><el-uploadaction="#":http-request="handleUpload":show-file-list="false"class="upload-btn"><el-buttontype="primary"size="large">上传图片检测</el-button></el-upload><divv-if="imageUrl"class="image-wrapper"ref="imgWrapper"><img:src="imageUrl"crossorigin="anonymous"@load="drawBoxes"/><!-- 动态绘制检测框 --><divv-for="(box, idx) in boxes":key="idx"class="yolo-box":style="{ left: box.box[0] + 'px', top: box.box[1] + 'px', width: (box.box[2] - box.box[0]) + 'px', height: (box.box[3] - box.box[1]) + 'px', borderColor: box.label === '闭眼' ? 'red' : 'green' }"><spanclass="tag">{{ box.label }} {{ box.confidence }}</span></div></div></div><!-- 右侧:数据与AI建议 --><divclass="info-area"v-if="resultData"><el-cardshadow="hover"><template#header>检测结果</template><p>识别对象:<strong>{{ mainLabel }}</strong></p><p>置信度:{{ maxConfidence }}%</p><p>耗时:{{ timeCost }}秒</p></el-card><el-cardshadow="hover"style="margin-top:20px;"><template#header>🤖 AI 智能分析 (DeepSeek)</template><divclass="ai-content"v-html="formattedReport"></div></el-card><el-buttontype="success"style="width:100%;margin-top:20px;"@click="exportPDF">导出 PDF 报告</el-button></div></div></template><scriptsetup>import{ref,computed}from'vue';importaxiosfrom'axios';import{ElMessage}from'element-plus';constimageUrl=ref('');constboxes=ref([]);constresultData=ref(null);constimgWrapper=ref(null);consthandleUpload=async(options)=>{constformData=newFormData();formData.append('file',options.file);try{constres=awaitaxios.post('http://localhost:8080/api/fatigue/upload',formData);if(res.data.code===200){resultData.value=res.data.data;// 假设后端返回了图片的访问URLimageUrl.value='http://localhost:8080/'+res.data.data.image_url;boxes.value=res.data.data.detections;ElMessage.success('检测完成');}}catch(e){ElMessage.error('检测失败');}};// 简单的坐标转换,实际需根据图片缩放比例计算constdrawBoxes=()=>{// 如果后端返回的是归一化坐标(0-1),需在此处乘以 imgWrapper.offsetWidth// 此处假设后端返回的是像素坐标};constmainLabel=computed(()=>resultData.value?.detections[0]?.label||'-');constmaxConfidence=computed(()=>(resultData.value?.detections[0]?.confidence*100).toFixed(2)||0);consttimeCost=computed(()=>resultData.value?.time_cost||0);// 将换行符转换为HTML <br>constformattedReport=computed(()=>{if(!resultData.value?.ai_report)return'';returnresultData.value.ai_report.replace(/\n/g,'<br>');});constexportPDF=()=>{// 调用后端生成PDF接口或使用前端库 jsPDFalert("正在生成PDF报告...");};</script><stylescoped>.container{display:flex;gap:20px;padding:20px;}.canvas-area{flex:2;text-align:center;border:1px dashed #ccc;min-height:400px;position:relative;}.image-wrapper{position:relative;display:inline-block;margin-top:20px;}.image-wrapper img{max-width:100%;}.yolo-box{position:absolute;border:2px solid;box-sizing:border-box;}.tag{background:rgba(0,0,0,0.6);color:#fff;font-size:12px;position:absolute;top:-20px;left:0;}.info-area{flex:1;}.ai-content{line-height:1.6;font-size:14px;color:#333;}</style>

6. 如何运行与训练模型

  1. 训练 YOLO 模型:

    • 收集驾驶员面部数据集(包含睁眼、闭眼、打哈欠)。
    • 使用RoboflowLabelImg进行标注。
    • 使用 Python 训练:
      fromultralyticsimportYOLO model=YOLO('yolov8n.pt')model.train(data='dataset.yaml',epochs=100,imgsz=640)
    • 将生成的best.pt放入 Python 项目的models/目录。
  2. 启动服务:

    • Python:python ai_service.py(端口 8000)
    • Java: 运行 SpringBoot 主类 (端口 8080)
    • Vue:npm run dev(端口 5173)
  3. 配置 DeepSeek:

    • 在 Java 代码中填入你的 DeepSeek API Key,即可实现截图中的“AI建议”功能。
← 返回列表