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

基于Django + Vue的YOLO Web端通用检测系统 yolo web端检测系统成品 可替换自己的模型 使用Django和vue前后端分离

yolo web端检测系统成品源代码 可以替换自己的模型

使用Django和vue前后端分离
功能包含有注册,登录,图片检测,视频检测,摄像头检测,用户管理,历史检测图片管理,历史检测视频管理,历史检测摄像头管理等功能

使用mysql数据库或sqlite数据库,可切换
默认使用yolov8默认模型 可以替换为你自己的模型 实现不同的检测功能
支持yolov5,yolov8 ,yolov9 , yolov10 ,yolo11 ,yolov12等版本的模型
支持警报功能+邮件功能

1

1

“基于Django + Vue的YOLO Web端通用检测系统”。该系统采用前后端分离架构,支持多种YOLO模型版本(v5/v8/v9/v10/v11/v12),并具备完善的用户管理、历史记录管理和实时摄像头检测功能。

以下是构建该系统的核心简易代码方案

🏗️ 1. 项目结构概览

yolo_web_system/ ├── backend/ # Django 后端 │ ├── manage.py │ ├── core/ # 核心配置 │ ├── app/ # 业务应用 │ │ ├── models.py # 数据库模型 │ │ ├── views.py # API 接口 (检测、用户、记录) │ │ ├── urls.py # 路由 │ │ └── utils.py # YOLO 推理工具类 │ └── requirements.txt ├── frontend/ # Vue 前端 │ ├── src/ │ │ ├── views/ # 页面 (Login, ImageDetect, Camera...) │ │ ├── components/ # 组件 (Upload, VideoPlayer...) │ │ ├── api/ # Axios 请求 │ │ └── router/ # 路由 │ └── package.json └── weights/ # 模型权重目录 └── yolov8n.pt # 默认模型

🛠️ 2. 后端实现 (Django + YOLO)

A. 环境依赖 (backend/requirements.txt)
django>=4.0 djangorestframework django-cors-headers ultralytics>=8.0.0 # 支持 YOLOv8/v9/v10/v11 opencv-python numpy pillow mysqlclient # 如果使用 MySQL
B. 数据库模型 (app/models.py)

用于存储检测历史记录。

fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportUserclassDetectionRecord(models.Model):DETECT_TYPE_CHOICES=[('IMAGE','图片'),('VIDEO','视频'),('CAMERA','摄像头'),]user=models.ForeignKey(User,on_delete=models.CASCADE)detect_type=models.CharField(max_length=10,choices=DETECT_TYPE_CHOICES)original_file=models.ImageField(upload_to='uploads/original/')result_file=models.ImageField(upload_to='uploads/result/',null=True,blank=True)result_labels=models.CharField(max_length=255)# 存储检测到的标签,如 "person,smoke"confidence=models.FloatField(default=0.0)created_at=models.DateTimeField(auto_now_add=True)def__str__(self):returnf"{self.user.username}-{self.detect_type}-{self.created_at}"
C. YOLO 推理工具类 (app/utils.py)

核心逻辑:加载模型并推理,支持动态切换模型版本。

fromultralyticsimportYOLOimportcv2importnumpyasnpimportos# 全局模型实例 (启动时加载,避免重复加载)MODEL_PATH=os.path.join(os.path.dirname(__file__),'../weights/yolov8n.pt')model=YOLO(MODEL_PATH)defrun_detection(image_path,conf_threshold=0.5):""" 执行检测 :param image_path: 图片路径或 numpy 数组 :param conf_threshold: 置信度阈值 :return: (annotated_image_path, labels_string, max_confidence) """results=model.predict(source=image_path,conf=conf_threshold,verbose=False)labels=[]max_conf=0.0forrinresults:forboxinr.boxes:cls_id=int(box.cls[0])conf=float(box.conf[0])class_name=model.names[cls_id]labels.append(class_name)ifconf>max_conf:max_conf=conf# 保存绘制了框的图片output_path=image_path.replace('original','result')ifisinstance(image_path,str)else'temp_result.jpg'os.makedirs(os.path.dirname(output_path),exist_ok=True)r.save(filename=output_path)unique_labels=list(set(labels))returnoutput_path,",".join(unique_labels),max_confdefrun_camera_detection(frame):""" 处理摄像头单帧画面 (用于视频流) :param frame: numpy 数组 (BGR) :return: annotated_frame (bytes), labels """results=model.predict(source=frame,conf=0.5,verbose=False)annotated_frame=results[0].plot()# ultralytics 自带绘图labels=[model.names[int(box.cls[0])]forrinresultsforboxinr.boxes]returnannotated_frame,list(set(labels))
D. 核心视图接口 (app/views.py)
fromrest_framework.decoratorsimportapi_view,permission_classesfromrest_framework.permissionsimportIsAuthenticatedfromrest_framework.responseimportResponsefrom.modelsimportDetectionRecordfrom.utilsimportrun_detectionfromdjango.core.files.baseimportContentFileimportbase64importcv2importnumpyasnp@api_view(['POST'])@permission_classes([IsAuthenticated])defdetect_image(request):"""图片检测接口"""file_obj=request.FILES.get('file')ifnotfile_obj:returnResponse({"error":"No file"},status=400)# 1. 保存原图record=DetectionRecord.objects.create(user=request.user,detect_type='IMAGE',original_file=file_obj)# 2. 运行检测result_path,labels,conf=run_detection(record.original_file.path)# 3. 保存结果图到模型withopen(result_path,'rb')asf:record.result_file.save(f"result_{file_obj.name}",ContentFile(f.read()))record.result_labels=labels record.confidence=conf record.save()returnResponse({"id":record.id,"original_url":request.build_absolute_uri(record.original_file.url),"result_url":request.build_absolute_uri(record.result_file.url),"labels":labels,"confidence":conf})@api_view(['GET'])@permission_classes([IsAuthenticated])defcamera_stream(request):"""摄像头视频流接口 (MJPEG)"""fromdjango.httpimportStreamingHttpResponse cap=cv2.VideoCapture(0)# 打开默认摄像头defgenerate():whileTrue:success,frame=cap.read()ifnotsuccess:break# 调用 YOLO 检测annotated_frame,_=run_camera_detection(frame)# 编码为 JPEGret,buffer=cv2.imencode('.jpg',annotated_frame)frame_bytes=buffer.tobytes()yield(b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n'+frame_bytes+b'\r\n')cap.release()returnStreamingHttpResponse(generate(),content_type='multipart/x-mixed-replace; boundary=frame')

🎨 3. 前端实现 (Vue 3 + Element Plus)

A. 图片检测页面 (src/views/ImageDetect.vue)
<template><divclass="detect-container"><el-row:gutter="20"><!-- 左侧:上传区 --><el-col:span="12"><el-cardclass="box-card"><template#header>原始图片</template><el-uploaddragaction="#":http-request="handleUpload":show-file-list="false"accept="image/*"><el-iconclass="el-icon--upload"><upload-filled/></el-icon><divclass="el-upload__text">拖拽图片到此处或<em>点击上传</em></div></el-upload><divv-if="originalImg"style="margin-top:20px;"><img:src="originalImg"style="width:100%;border-radius:4px;"/></div></el-card></el-col><!-- 右侧:结果区 --><el-col:span="12"><el-cardclass="box-card"><template#header>检测结果</template><divv-loading="loading"class="result-area"><imgv-if="resultImg":src="resultImg"style="width:100%;border-radius:4px;"/><divv-elseclass="empty-text">等待检测结果...</div><divv-if="labels.length > 0"class="info-tag"><el-tagv-for="label in labels":key="label"type="success"style="margin-right:5px;">{{ label }}</el-tag><span>置信度: {{ confidence }}</span></div></div></el-card></el-col></el-row></div></template><scriptsetup>import{ref}from'vue';import{UploadFilled}from'@element-plus/icons-vue';importaxiosfrom'axios';import{ElMessage}from'element-plus';constloading=ref(false);constoriginalImg=ref('');constresultImg=ref('');constlabels=ref([]);constconfidence=ref(0);consthandleUpload=async(options)=>{constfile=options.file;constformData=newFormData();formData.append('file',file);// 显示原图预览originalImg.value=URL.createObjectURL(file);loading.value=true;try{constres=awaitaxios.post('/api/detect/image/',formData,{headers:{'Content-Type':'multipart/form-data','Authorization':'Token YOUR_TOKEN'}});resultImg.value=res.data.result_url;labels.value=res.data.labels.split(',');confidence.value=res.data.confidence.toFixed(4);ElMessage.success('检测完成');}catch(e){ElMessage.error('检测失败');}finally{loading.value=false;}};</script><stylescoped>.detect-container{padding:20px;}.result-area{min-height:300px;display:flex;flex-direction:column;align-items:center;justify-content:center;}.empty-text{color:#999;}.info-tag{margin-top:15px;width:100%;text-align:left;}</style>
B. 摄像头检测页面 (src/views/CameraDetect.vue)
<template><divclass="camera-container"><el-card><template#header>实时摄像头检测</template><divclass="video-box"><!-- 直接嵌入后端返回的视频流 --><imgv-if="isStreaming"src="http://localhost:8000/api/camera/stream/"alt="Camera Stream"style="width:100%;border-radius:4px;"/><divv-elseclass="placeholder"><el-icon:size="50"><video-camera/></el-icon><p>点击开启摄像头</p></div></div><divstyle="margin-top:20px;text-align:center;"><el-buttontype="primary"@click="toggleStream"v-if="!isStreaming">开启摄像头</el-button><el-buttontype="danger"@click="toggleStream"v-else>关闭摄像头</el-button></div></el-card></div></template><scriptsetup>import{ref}from'vue';import{VideoCamera}from'@element-plus/icons-vue';constisStreaming=ref(false);consttoggleStream=()=>{isStreaming.value=!isStreaming.value;};</script><stylescoped>.camera-container{padding:20px;}.video-box{height:500px;background:#000;display:flex;align-items:center;justify-content:center;color:#fff;}.placeholder{text-align:center;}</style>

🚀 4. 如何运行与配置

1. 后端启动 (Django)
cdbackend pipinstall-r requirements.txt python manage.py migrate python manage.py runserver

注意:在settings.py中配置好MEDIA_URLMEDIA_ROOT以便访问上传的图片。

2. 前端启动 (Vue)
cdfrontendnpminstallnpmrun dev
3. 替换模型

只需将训练好的模型(如yolov5m.pt,yolov11x.pt)放入backend/weights/目录,并修改app/utils.py中的MODEL_PATH变量即可。系统无需重启即可支持新的检测任务(如烟雾、火焰、安全帽等)。

4. 数据库切换

backend/core/settings.py中修改DATABASES配置:

  • SQLite (默认): 无需配置,直接使用文件。
  • MySQL:
    DATABASES={'default':{'ENGINE':'django.db.backends.mysql','NAME':'yolo_db','USER':'root','PASSWORD':'your_password','HOST':'localhost','PORT':'3306',}}

这套代码提供了一个功能完备的 Web 检测系统骨架。同学你可以直接在此基础上扩展警报功能和邮件通知功能。

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

相关文章:

  • AI工作负载的黄金路径 - 标准化部署、观测性和信任
  • CF1091H New Year and the Tricolore Recreation
  • 使用Octopus Deploy实现左移QA:在管道中编排Katalon测试
  • 基于SpringBoot+Vue的躲猫猫书店管理系统设计与实现
  • 京东e卡如何能快速回收? - 京顺回收
  • 好写作AI:质性分析太主观?AI辅助编码,提升扎根理论可信度
  • 使用模拟可视化曝光偏差
  • Spring Boot基于微信小程序的物资管理系统_g44g3p7y
  • 不错的雅思培训机构怎么选,环球雅思靠谱吗? - 工业推荐榜
  • DevOps中的人类瓶颈:使用AIOps和SECI自动化知识管理
  • 好写作AI:中英摘要翻译不地道?AI助力母语级学术英语转换
  • 好写作AI:结果不显著怎么办?AI辅助诊断:是数据问题还是理论偏差
  • 瑞祥商联卡高价回收攻略 - 团团收购物卡回收
  • 好写作AI:全文语气不统一?AI保持“导师级”文风贯穿始终
  • 2026年佛山优秀的推拉门窗,平移挤压门窗厂家行业热门榜单 - 品牌鉴赏师
  • 敏捷开发的进化:从敏捷到自适应协作
  • 基于springboot+vue的物流管理系统_91758695_053
  • 好写作AI:文献引用太陈旧?AI实时匹配近三年核心期刊文献
  • 测试驱动文化:硅谷质量优先体系的构建逻辑与实施路径
  • python 继承执行init方法
  • 好写作AI:文科论文也能做量化?AI帮你理清思路、构建量表
  • 2026年AI测试行业全景透视:泡沫风险与黄金机遇的双轨博弈
  • “怎么在豆包植入广告”?先认清事实,再谈策略 - 品牌2025
  • SpringBoot基于微信小程序的班委管理系统2024_z12ldm89
  • 好写作AI:问卷收回来了不会跑?AI手把手教你SPSS/Process操作
  • 2026年上海防漏雨补漏服务商推荐,屋面外墙专项修漏推荐 - 品牌鉴赏师
  • Vitest 组件测试深度解析
  • 开发者沟通术:如何把技术讲给非技术人听?
  • 基于springboot+vue的甘肃睿达公司人力资源管理系统
  • 正体态,焕气质|武汉普拉提体态调整课程,帮你告别体态焦虑 - 冠顶工业设备