当前位置: 首页 > news >正文

基于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. 部署与运行

  1. 启动后端

    • 配置settings.py中的数据库连接。
    • 运行python manage.py makemigrationsmigrate
    • 运行python manage.py runserver
  2. 启动前端

    • 进入frontend目录。
    • 运行npm install
    • 运行npm run dev
  3. 管理员账号

    • 运行python manage.py createsuperuser创建管理员,登录/admin查看后台数据。

这套代码框架涵盖了从AI 推理前端展示的完整流程,你可以直接基于此进行二次开发,例如添加视频流检测(使用 OpenCV 读取 RTSP 流)或更复杂的 RAG 问答功能。

http://www.jsqmd.com/news/677635/

相关文章:

  • Multisim里那些新手必踩的坑:从元件库找不到型号到仿真结果不对,一篇讲清避坑指南
  • 别下716GB了!用这个18GB的Light-HaGRID手势数据集,快速上手YOLOv5训练
  • Hermes Agent 使用与启动指南
  • 2026年值得合作的进口喉镜优质供应商推荐 - 品牌推荐大师1
  • 实地探访:四流喂丝机工厂在华北的布局,为何选择与 合作? - 新闻快传
  • LumenPnP开源贴片机完整指南:如何打造你的专属电子制造工作站
  • AI教材编写必备!低查重AI工具,轻松生成高质量教材内容!
  • 5个技巧让自动驾驶车辆在复杂路况下安全行驶:CILQR约束优化算法完全指南
  • 别再乱用kmalloc了!Linux内核驱动开发中内存分配函数的选择避坑指南
  • Proteus仿真有什么问题?怎么解决?
  • 告别单调界面:用ESP32和LVGL 8.1的Style背景API打造炫酷UI(附渐变/图片实战代码)
  • macOS窗口置顶终极指南:用Topit彻底释放多任务处理潜能
  • 豪城悦洁家政服务:亳州房屋渗水维修公司 - LYL仔仔
  • 如何快速掌握bilibili-downloader:新手也能上手的B站视频下载完整教程
  • MySQL外键怎么定义?数据关联怎么更清晰稳固?
  • 别再手动调优了!用RHEL/CentOS自带的Tuned工具,5分钟搞定Linux服务器性能配置
  • 收藏!小白/程序员快速上手大模型:Hermes Agent 完全指南与生态地图
  • tkinter按钮进阶玩法:从方形到圆角,详解TinyUI中button2的样式定制与事件绑定避坑指南
  • 2026年湖南长沙高端别墅装修与大平层全案定制服务对比指南 - 年度推荐企业名录
  • 为什么92%的Docker安全事件源于签名绕过?27步工业级验证流程,含cosign、notary v2、TUF三框架实测对比
  • EF Core 10向量索引如何与SQL Server 2022 HNSW无缝协同?——微软认证架构师披露内部性能调优参数表(含T-SQL向量化执行计划解读)
  • Douyin-Downloader:Python抖音批量下载工具的技术深度解析与实战指南
  • 泉州鼎盛拆除:泉州水泥黄沙出售电话 - LYL仔仔
  • fluent数值波高衰减怎么设置?为什么会出现衰减?
  • 告别NDT和ICP:用VoxelMap实现更鲁棒、更精准的LiDAR SLAM(附KITTI实测对比)
  • 别再手动拖菜单了!用Creo Toolkit自动化定制你的专属工作流菜单栏
  • LeaguePrank:5分钟打造你的专属英雄联盟形象
  • 机器人关节精密加工:GDT形位公差控制与装配卡滞对策深度解析 - 莱图加精密零件加工
  • EdgeRemover:彻底告别Windows系统Edge浏览器卸载难题
  • 如何在本地实现OBS实时字幕与翻译?LocalVocal插件完整指南