基于Django+Vue3与YOLO深度学习的火灾烟雾智能监测系统采用Django+Vue3前后端分离架构,含用户端与管理端界面,具备监控区域管理、火情记录归档、任务管理、智能问答、数据大屏、记录导出

张开发
2026/4/21 17:21:27 15 分钟阅读

分享文章

基于Django+Vue3与YOLO深度学习的火灾烟雾智能监测系统采用Django+Vue3前后端分离架构,含用户端与管理端界面,具备监控区域管理、火情记录归档、任务管理、智能问答、数据大屏、记录导出
智慧火灾检测-火灾烟雾智能检测系统基于DjangoVue3与YOLO深度学习的火灾烟雾智能监测系统基于YOLO深度学习模型支持图片、批量图片、视频、摄像头实时检测可识别火焰与烟雾并进行提示。采用DjangoVue3前后端分离架构含用户端与管理端界面具备监控区域管理、火情记录归档、任务管理、智能问答、数据大屏、记录导出等功能。内含MySQL数据库文件、启动脚本、部署教程、初始化SQL文件在这里插入图片描述11这是一套非常完整且具备工业级应用潜力的火灾烟雾智能检测系统。根据你提供的截图包括注册、登录、火情检测中心、数据大屏、个人中心、管理员后台该系统不仅包含了核心的 AI 识别功能还具备完善的业务流转逻辑。由于这是一个全栈工程代码量较大我将为你提供核心架构设计、数据库模型、YOLO 推理逻辑以及前后端关键代码帮助你快速复现这套系统。1. 系统架构设计前端Vue 3 Vite Element Plus ECharts用于数据大屏。后端Django Django REST Framework (DRF)。AI 核心Ultralytics YOLOv8针对火焰和烟雾进行训练。数据库MySQL。2. 数据库模型设计 (Django)根据截图中的“检测记录”、“监控区域”、“用户管理”我们需要设计以下核心模型。文件路径backend/detect_system/models.pyfromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportAbstractUser# 1. 用户表 (扩展自带用户)classUser(AbstractUser):phonemodels.CharField(max_length11,blankTrue,nullTrue,verbose_name手机号)avatarmodels.ImageField(upload_toavatars/,defaultavatars/default.png,verbose_name头像)rolemodels.CharField(max_length10,choices[(admin,管理员),user,普通用户)],defaultuser)# 2. 监控区域表classMonitorArea(models.Model):namemodels.CharField(max_length100,verbose_name区域名称)locationmodels.CharField(max_length200,verbose_name地理位置描述)descriptionmodels.TextField(blankTrue,verbose_name备注)def__str__(self):returnself.name# 3. 检测记录表classDetectionRecord(models.Model):usermodels.ForeignKey(User,on_deletemodels.CASCADE,verbose_name检测用户)areamodels.ForeignKey(MonitorArea,on_deletemodels.SET_NULL,nullTrue,verbose_name监控区域)imagemodels.ImageField(upload_todetection_images/,verbose_name检测图片)result_imagemodels.ImageField(upload_toresult_images/,verbose_name结果图片)fire_countmodels.IntegerField(default0,verbose_name火焰数量)smoke_countmodels.IntegerField(default0,verbose_name烟雾数量)confidencemodels.FloatField(verbose_name最高置信度)risk_levelmodels.CharField(max_length10,choices[(low,低风险),(medium,中风险),(high,高风险)],defaultlow)created_atmodels.DateTimeField(auto_now_addTrue,verbose_name检测时间)def__str__(self):returnf{self.user.username}-{self.created_at}3. AI 核心推理代码 (YOLOv8)这是系统的“大脑”。你需要加载训练好的best.pt模型针对火焰和烟雾训练。文件路径backend/utils/yolo_detector.pyfromultralyticsimportYOLOimportcv2importnumpyasnpimportos# 加载模型 (确保 best.pt 在同级目录或指定路径)MODEL_PATHos.path.join(os.path.dirname(__file__),weights,best.pt)modelYOLO(MODEL_PATH)classFireSmokeDetector:def__init__(self):self.classes{0:Fire,1:Smoke}# 假设 0是火焰1是烟雾defdetect_image(self,image_path,conf_threshold0.25): 单张图片检测 # 读取图片imgcv2.imread(image_path)ifimgisNone:returnNone,图片读取失败# YOLO 推理resultsmodel(img,confconf_threshold)resultresults[0]fire_count0smoke_count0max_conf0.0# 解析结果并绘图forboxinresult.boxes:x1,y1,x2,y2map(int,box.xyxy[0].tolist())confbox.conf[0].item()clsint(box.cls[0].item())ifconfmax_conf:max_confconf labelself.classes[cls]color(0,0,255)ifcls0else(0,165,255)# 火焰红烟雾橙# 计数ifcls0:fire_count1else:smoke_count1# 绘制矩形框和标签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)# 判断风险等级risklowiffire_count0orsmoke_count3:riskhighelifsmoke_count0:riskmediumreturn{image:img,# OpenCV 格式图像fire_count:fire_count,smoke_count:smoke_count,risk_level:risk,max_conf:max_conf},success4. 后端接口实现 (Django REST Framework)处理图片上传、调用 AI、保存记录。文件路径backend/detect_system/views.pyfromrest_framework.decoratorsimportapi_view,permission_classesfromrest_framework.permissionsimportIsAuthenticatedfromrest_framework.responseimportResponsefrom.modelsimportDetectionRecord,MonitorAreafromutils.yolo_detectorimportFireSmokeDetectorimportcv2importosfromdjango.confimportsettingsimportuuid detectorFireSmokeDetector()api_view([POST])permission_classes([IsAuthenticated])defdetect_fire_smoke(request): 上传并检测火灾烟雾 image_filerequest.FILES.get(image)area_idrequest.data.get(area_id)conf_thresholdfloat(request.data.get(conf_threshold,0.25))ifnotimage_file:returnResponse({error:未上传文件},status400)# 1. 保存原始图片unique_filenamef{uuid.uuid4()}.jpgoriginal_pathos.path.join(settings.MEDIA_ROOT,uploads,unique_filename)os.makedirs(os.path.dirname(original_path),exist_okTrue)withopen(original_path,wb)asdestination:forchunkinimage_file.chunks():destination.write(chunk)# 2. 调用 YOLO 模型检测result_data,msgdetector.detect_image(original_path,conf_threshold)ifmsg!success:returnResponse({error:msg},status500)# 3. 保存结果图片result_img_pathos.path.join(settings.MEDIA_ROOT,results,fresult_{unique_filename})os.makedirs(os.path.dirname(result_img_path),exist_okTrue)cv2.imwrite(result_img_path,result_data[image])# 4. 存入数据库areaMonitorArea.objects.get(idarea_id)ifarea_idelseNonerecordDetectionRecord.objects.create(userrequest.user,areaarea,imagefuploads/{unique_filename},result_imagefresults/result_{unique_filename},fire_countresult_data[fire_count],smoke_countresult_data[smoke_count],confidenceresult_data[max_conf],risk_levelresult_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_URLfresults/result_{unique_filename})})5. 前端核心代码 (Vue 3 ECharts)检测页面 (上传图片与展示结果)文件路径frontend/src/views/Detection.vuetemplatedivclassdetection-containerdivclassleft-panelel-uploadclassupload-demodragaction#:auto-uploadfalse:on-changehandleFileChangeel-iconclassel-icon--uploadupload-filled//el-icondivclassel-upload__text点击或拖拽上传图片/div/el-uploadel-buttontypeprimaryclicksubmitUploadstylewidth:100%;margin-top:20px;开始检测/el-button/divdivclassright-paneldivv-ifresultImageclassresult-boxh3检测结果/h3img:srcresultImagealt检测结果/divclassstatsspan火焰: {{ fireCount }}/spanspan烟雾: {{ smokeCount }}/spanspan:classriskLevel high ? text-red : text-green风险: {{ riskLevel }}/span/div/div/div/div/templatescriptsetupimport{ref}fromvueimportaxiosfromaxiosconstselectedFileref(null)constresultImageref()constfireCountref(0)constsmokeCountref(0)constriskLevelref()consthandleFileChange(file){selectedFilefile.raw}constsubmitUploadasync(){if(!selectedFile)returnconstformDatanewFormData()formData.append(image,selectedFile)formData.append(area_id,1)// 示例区域IDtry{constresawaitaxios.post(/api/detect/,formData,{headers:{Content-Type:multipart/form-data}})resultImage.valueres.data.result_image_url fireCount.valueres.data.fire_count smokeCount.valueres.data.smoke_count riskLevel.valueres.data.risk_level}catch(error){console.error(检测失败,error)}}/scriptstylescoped.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.vuetemplatedivclassdashboarddivclasschart-itemh3近7天检测趋势/h3divreflineChartstylewidth:100%;height:300px;/div/divdivclasschart-itemh3火焰/烟雾占比/h3divrefpieChartstylewidth:100%;height:300px;/div/div/div/templatescriptsetupimport{onMounted,ref}fromvueimport*asechartsfromechartsimportaxiosfromaxiosconstlineChartref(null)constpieChartref(null)onMounted(async(){// 获取数据const{data}awaitaxios.get(/api/stats/dashboard/)// 初始化折线图constlineInstanceecharts.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}}]})// 初始化饼图constpieInstanceecharts.init(pieChart.value)pieInstance.setOption({series:[{type:pie,data:[{value:data.fire_total,name:火焰},{value:data.smoke_total,name:烟雾}],color:[#FF4D4F,#FAAD14]}]})})/script6. 部署与运行启动后端配置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 问答功能。

更多文章