基于Django+Vue3与YOLO深度学习的火灾烟雾智能监测系统采用Django+Vue3前后端分离架构,含用户端与管理端界面,具备监控区域管理、火情记录归档、任务管理、智能问答、数据大屏、记录导出
智慧火灾检测-火灾烟雾智能检测系统基于Django+Vue3与YOLO深度学习的火灾烟雾智能监测系统
,基于YOLO深度学习模型,支持图片、批量图片、视频、摄像头实时检测,可识别火焰与烟雾并进行提示。
采用Django+Vue3前后端分离架构,含用户端与管理端界面,具备监控区域管理、火情记录归档、任务管理、智能问答、数据大屏、记录导出等功能。
内含MySQL数据库文件、启动脚本、部署教程、初始化SQL文件
在这里插入图片描述
1
1
这是一套非常完整且具备工业级应用潜力的火灾烟雾智能检测系统。根据你提供的截图(包括注册、登录、火情检测中心、数据大屏、个人中心、管理员后台),该系统不仅包含了核心的 AI 识别功能,还具备完善的业务流转逻辑。
由于这是一个全栈工程,代码量较大,我将为你提供核心架构设计、数据库模型、YOLO 推理逻辑以及前后端关键代码,帮助你快速复现这套系统。
1. 系统架构设计
- 前端:Vue 3 + Vite + Element Plus + ECharts(用于数据大屏)。
- 后端:Django + Django REST Framework (DRF)。
- AI 核心:Ultralytics YOLOv8(针对火焰和烟雾进行训练)。
- 数据库:MySQL。
2. 数据库模型设计 (Django)
根据截图中的“检测记录”、“监控区域”、“用户管理”,我们需要设计以下核心模型。
文件路径:backend/detect_system/models.py
fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportAbstractUser# 1. 用户表 (扩展自带用户)classUser(AbstractUser):phone=models.CharField(max_length=11,blank=True,null=True,verbose_name="手机号")avatar=models.ImageField(upload_to='avatars/',default='avatars/default.png',verbose_name="头像")role=models.CharField(max_length=10,choices=[('admin','管理员'),'user','普通用户')],default='user')# 2. 监控区域表classMonitorArea(models.Model):name=models.CharField(max_length=100,verbose_name="区域名称")location=models.CharField(max_length=200,verbose_name="地理位置描述")description=models.TextField(blank=True,verbose_name="备注")def__str__(self):returnself.name# 3. 检测记录表classDetectionRecord(models.Model):user=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="检测用户")area=models.ForeignKey(MonitorArea,on_delete=models.SET_NULL,null=True,verbose_name="监控区域")image=models.ImageField(upload_to='detection_images/',verbose_name="检测图片")result_image=models.ImageField(upload_to='result_images/',verbose_name="结果图片")fire_count=models.IntegerField(default=0,verbose_name="火焰数量")smoke_count=models.IntegerField(default=0,verbose_name="烟雾数量")confidence=models.FloatField(verbose_name="最高置信度")risk_level=models.CharField(max_length=10,choices=[('low','低风险'),('medium','中风险'),('high','高风险')],default='low')created_at=models.DateTimeField(auto_now_add=True,verbose_name="检测时间")def__str__(self):returnf"{self.user.username}-{self.created_at}"3. AI 核心推理代码 (YOLOv8)
这是系统的“大脑”。你需要加载训练好的best.pt模型(针对火焰和烟雾训练)。
文件路径:backend/utils/yolo_detector.py
fromultralyticsimportYOLOimportcv2importnumpyasnpimportos# 加载模型 (确保 best.pt 在同级目录或指定路径)MODEL_PATH=os.path.join(os.path.dirname(__file__),'weights','best.pt')model=YOLO(MODEL_PATH)classFireSmokeDetector:def__init__(self):self.classes={0:'Fire',1:'Smoke'}# 假设 0是火焰,1是烟雾defdetect_image(self,image_path,conf_threshold=0.25):""" 单张图片检测 """# 读取图片img=cv2.imread(image_path)ifimgisNone:returnNone,"图片读取失败"# YOLO 推理results=model(img,conf=conf_threshold)result=results[0]fire_count=0smoke_count=0max_conf=0.0# 解析结果并绘图forboxinresult.boxes:x1,y1,x2,y2=map(int,box.xyxy[0].tolist())conf=box.conf[0].item()cls=int(box.cls[0].item())ifconf>max_conf:max_conf=conf label=self.classes[cls]color=(0,0,255)ifcls==0else(0,165,255)# 火焰红,烟雾橙# 计数ifcls==0:fire_count+=1else:smoke_count+=1# 绘制矩形框和标签cv2.rectangle(img,(x1,y1),(x2,y2),color,2)cv2.putText(img,f'{label}{conf:.2f}',(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,color,2)# 判断风险等级risk="low"iffire_count>0orsmoke_count>3:risk="high"elifsmoke_count>0:risk="medium"return{"image":img,# OpenCV 格式图像"fire_count":fire_count,"smoke_count":smoke_count,"risk_level":risk,"max_conf":max_conf},"success"4. 后端接口实现 (Django REST Framework)
处理图片上传、调用 AI、保存记录。
文件路径:backend/detect_system/views.py
fromrest_framework.decoratorsimportapi_view,permission_classesfromrest_framework.permissionsimportIsAuthenticatedfromrest_framework.responseimportResponsefrom.modelsimportDetectionRecord,MonitorAreafromutils.yolo_detectorimportFireSmokeDetectorimportcv2importosfromdjango.confimportsettingsimportuuid detector=FireSmokeDetector()@api_view(['POST'])@permission_classes([IsAuthenticated])defdetect_fire_smoke(request):""" 上传并检测火灾烟雾 """image_file=request.FILES.get('image')area_id=request.data.get('area_id')conf_threshold=float(request.data.get('conf_threshold',0.25))ifnotimage_file:returnResponse({"error":"未上传文件"},status=400)# 1. 保存原始图片unique_filename=f"{uuid.uuid4()}.jpg"original_path=os.path.join(settings.MEDIA_ROOT,'uploads',unique_filename)os.makedirs(os.path.dirname(original_path),exist_ok=True)withopen(original_path,'wb+')asdestination:forchunkinimage_file.chunks():destination.write(chunk)# 2. 调用 YOLO 模型检测result_data,msg=detector.detect_image(original_path,conf_threshold)ifmsg!="success":returnResponse({"error":msg},status=500)# 3. 保存结果图片result_img_path=os.path.join(settings.MEDIA_ROOT,'results',f"result_{unique_filename}")os.makedirs(os.path.dirname(result_img_path),exist_ok=True)cv2.imwrite(result_img_path,result_data['image'])# 4. 存入数据库area=MonitorArea.objects.get(id=area_id)ifarea_idelseNonerecord=DetectionRecord.objects.create(user=request.user,area=area,image=f'uploads/{unique_filename}',result_image=f'results/result_{unique_filename}',fire_count=result_data['fire_count'],smoke_count=result_data['smoke_count'],confidence=result_data['max_conf'],risk_level=result_data['risk_level'])# 5. 返回结果returnResponse({"record_id":record.id,"fire_count":result_data['fire_count'],"smoke_count":result_data['smoke_count'],"risk_level":result_data['risk_level'],"result_image_url":request.build_absolute_uri(settings.MEDIA_URL+f'results/result_{unique_filename}')})5. 前端核心代码 (Vue 3 + ECharts)
检测页面 (上传图片与展示结果)
文件路径:frontend/src/views/Detection.vue
<template><divclass="detection-container"><divclass="left-panel"><el-uploadclass="upload-demo"dragaction="#":auto-upload="false":on-change="handleFileChange"><el-iconclass="el-icon--upload"><upload-filled/></el-icon><divclass="el-upload__text">点击或拖拽上传图片</div></el-upload><el-buttontype="primary"@click="submitUpload"style="width:100%;margin-top:20px;">开始检测</el-button></div><divclass="right-panel"><divv-if="resultImage"class="result-box"><h3>检测结果</h3><img:src="resultImage"alt="检测结果"/><divclass="stats"><span>火焰: {{ fireCount }}</span><span>烟雾: {{ smokeCount }}</span><span:class="riskLevel === 'high' ? 'text-red' : 'text-green'">风险: {{ riskLevel }}</span></div></div></div></div></template><scriptsetup>import{ref}from'vue'importaxiosfrom'axios'constselectedFile=ref(null)constresultImage=ref('')constfireCount=ref(0)constsmokeCount=ref(0)constriskLevel=ref('')consthandleFileChange=(file)=>{selectedFile=file.raw}constsubmitUpload=async()=>{if(!selectedFile)returnconstformData=newFormData()formData.append('image',selectedFile)formData.append('area_id',1)// 示例区域IDtry{constres=awaitaxios.post('/api/detect/',formData,{headers:{'Content-Type':'multipart/form-data'}})resultImage.value=res.data.result_image_url fireCount.value=res.data.fire_count smokeCount.value=res.data.smoke_count riskLevel.value=res.data.risk_level}catch(error){console.error("检测失败",error)}}</script><stylescoped>.detection-container{display:flex;gap:20px;padding:20px;background:#1f1f2e;height:100vh;}.left-panel, .right-panel{flex:1;background:#2b2b3b;padding:20px;border-radius:8px;}img{max-width:100%;border-radius:4px;}.text-red{color:#ff4d4f;}.text-green{color:#52c41a;}</style>数据大屏 (ECharts 可视化)
文件路径:frontend/src/views/Dashboard.vue
<template><divclass="dashboard"><divclass="chart-item"><h3>近7天检测趋势</h3><divref="lineChart"style="width:100%;height:300px;"></div></div><divclass="chart-item"><h3>火焰/烟雾占比</h3><divref="pieChart"style="width:100%;height:300px;"></div></div></div></template><scriptsetup>import{onMounted,ref}from'vue'import*asechartsfrom'echarts'importaxiosfrom'axios'constlineChart=ref(null)constpieChart=ref(null)onMounted(async()=>{// 获取数据const{data}=awaitaxios.get('/api/stats/dashboard/')// 初始化折线图constlineInstance=echarts.init(lineChart.value)lineInstance.setOption({xAxis:{type:'category',data:data.dates},yAxis:{type:'value'},series:[{data:data.counts,type:'line',smooth:true,itemStyle:{color:'#5470C6'}}]})// 初始化饼图constpieInstance=echarts.init(pieChart.value)pieInstance.setOption({series:[{type:'pie',data:[{value:data.fire_total,name:'火焰'},{value:data.smoke_total,name:'烟雾'}],color:['#FF4D4F','#FAAD14']}]})})</script>6. 部署与运行
启动后端:
- 配置
settings.py中的数据库连接。 - 运行
python manage.py makemigrations和migrate。 - 运行
python manage.py runserver。
- 配置
启动前端:
- 进入
frontend目录。 - 运行
npm install。 - 运行
npm run dev。
- 进入
管理员账号:
- 运行
python manage.py createsuperuser创建管理员,登录/admin查看后台数据。
- 运行
这套代码框架涵盖了从AI 推理到前端展示的完整流程,你可以直接基于此进行二次开发,例如添加视频流检测(使用 OpenCV 读取 RTSP 流)或更复杂的 RAG 问答功能。
