
技术 | 角色 | 一句话理解 |
|---|---|---|
Python 3.8~3.10 | 编程语言 | 整个项目的母语 |
Django 4.x+ | Web后端框架 | 网站的"大脑",处理请求、管理数据、返回页面 |
YOLOv8 | 目标检测模型 | 网站的"眼睛",看懂图片里有什么 |
PyTorch | 深度学习引擎 | YOLOv8的"心脏",驱动模型运行 |
LabelImg | 数据标注工具 | 给训练图片画框、打标签 |
SQLite | 数据库 | Django自带,零配置,够用 |
HTML + CSS | 前端页面 | 上传图片、展示结果的界面 |
🎯 核心逻辑:用户上传图片 → Django接收 → 调用YOLOv8检测 → 返回结果 → 页面展示。 就这么简单。
去官网下载 Miniconda3(Windows 64位),安装时一路"下一步"。安装完后,打开 Miniconda Prompt(不是系统CMD!)。
bash1# 创建环境(Python 3.8,兼容性最优)
2conda create -n yolov8_env python=3.8 -y
3
4# 激活环境(之后所有操作都在这里)
5conda activate yolov8_env
6激活成功后,命令行前会显示 (yolov8_env)。
场景 | 命令 |
|---|---|
CPU版(所有电脑可用,新手首选) | pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple |
GPU版(NVIDIA显卡,训练快10倍) | pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 |
验证安装:
bash1python -c "import torch; print(torch.cuda.is_available())"
2# 显示 True = GPU可用,False = 用CPU版,完全没问题
3bash1# 安装YOLOv8(Ultralytics官方库,一行搞定)
2pip install ultralytics -i https://pypi.tuna.tsinghua.edu.cn/simple
3
4# 安装Django
5pip install django -i https://pypi.tuna.tsinghua.edu.cn/simple
6
7# 安装标注工具LabelImg
8pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple
9
10# 安装视频处理依赖
11pip install moviepy -i https://pypi.tuna.tsinghua.edu.cn/simple
12💡 全部用国内清华源,下载速度提升5~10倍,再也不用等GitHub超时了。
bash1# 验证YOLOv8
2python -c "from ultralytics import YOLO; print('YOLOv8 安装成功!')"
3
4# 验证Django
5python -c "import django; print('Django 版本:', django.VERSION)"
6
7# 验证LabelImg
8labelimg # 弹出界面即成功
9在训练自己的模型之前,先用官方预训练模型跑通流程,建立信心。
python1from ultralytics import YOLO
2
3# 加载官方预训练模型(首次运行自动下载,约200MB)
4model = YOLO('yolov8n.pt') # nano版,CPU也能跑,35ms/张
5
6# 检测一张图片
7results = model('test.jpg')
8
9# 显示结果(自动弹窗)
10results[0].show()
11
12# 保存结果
13results[0].save(filename='result.jpg')
14模型 | 参数量 | 速度(CPU) | 适用场景 |
|---|---|---|---|
YOLOv8n | 3.2M | ~35ms | 实时检测、边缘设备 ✅ |
YOLOv8s | 11.2M | ~50ms | 平衡速度与精度 ✅ |
YOLOv8m | 25.9M | ~80ms | 精度优先 |
YOLOv8l | 43.7M | ~120ms | 服务器高精度 |
YOLOv8x | 68.2M | ~200ms | 追求极致 |
🎯 新手直接用 yolov8n.pt,轻量快速,CPU就能跑,先把流程跑通再说。
Open Dir → 选择你的图片文件夹(必须是英文路径!)W 框选目标,输入标签(如 cat、dog,大小写一致)Ctrl+S 保存(自动生成 .txt 标注文件)D 切换下一张,至少标注 20~50张1datasets/
2├── images/
3│ ├── train/ # 70%~80%的图片
4│ └── val/ # 20%~30%的图片
5├── labels/
6│ ├── train/ # 对应train图片的.txt标注
7│ └── val/ # 对应val图片的.txt标注
8└── data.yaml # 数据集配置文件
9yaml1path: datasets/
2train: images/train
3val: images/val
4
5nc: 2 # 类别数量(比如cat和dog,nc=2)
6names: ['cat', 'dog'] # 类别名,必须和标注一致
7bash1yolo detect train model=yolov8n.pt data=datasets/data.yaml epochs=50 imgsz=640 batch=4
2参数 | 说明 |
|---|---|
model=yolov8n.pt | 使用nano预训练权重,训练更快 |
data=data.yaml | 指定数据集配置 |
epochs=50 | 训练50轮(新手够用) |
imgsz=640 | 输入图片尺寸 |
batch=4 | 每批4张图(显存小就改成2) |
训练完成后,模型在:
1runs/detect/train/weights/best.pt ← 这就是你训练好的模型!
2🔥 常见坑:CUDA out of memory? 解决方案:① 减小
batch为 2;② 减小imgsz为 512;③ 开启梯度累积accum=2;④ 换更小的模型yolov8n.pt。
bash1# 进入你的工作目录
2cd D:\projects
3
4# 创建项目
5django-admin startproject mysite
6
7# 进入项目
8cd mysite
9
10# 创建检测应用
11python manage.py startapp detector
12项目结构:
1mysite/
2├── mysite/ # 项目配置
3│ ├── settings.py # 核心配置
4│ ├── urls.py # 路由入口
5│ └── wsgi.py
6├── detector/ # 检测应用(我们的核心代码在这里)
7│ ├── views.py # 视图函数
8│ ├── urls.py # 应用路由
9│ └── models.py
10└── manage.py
11打开 mysite/settings.py:
python1INSTALLED_APPS = [
2 'django.contrib.admin',
3 'django.contrib.auth',
4 'django.contrib.contenttypes',
5 'django.contrib.sessions',
6 'django.contrib.messages',
7 'django.contrib.staticfiles',
8 'detector', # ← 加上我们的应用
9]
10
11# 媒体文件配置(存放上传的图片)
12MEDIA_URL = '/media/'
13MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
14detector/views.py:
python1from django.shortcuts import render
2
3def index(request):
4 return render(request, 'detector/index.html')
5detector/urls.py(新建):
python1from django.urls import path
2from . import views
3
4urlpatterns = [
5 path('', views.index, name='index'),
6]
7mysite/urls.py:
python1from django.contrib import admin
2from django.urls import path, include
3from django.conf import settings
4from django.conf.urls.static import static
5
6urlpatterns = [
7 path('admin/', admin.site.urls),
8 path('', include('detector.urls')),
9] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
10运行服务:
bash1python manage.py runserver
2访问 http://127.0.0.1:8000/ → 看到你的第一个Django页面!🎉
这是整篇教程的灵魂所在——让Web页面和AI模型真正对话。
python1import os
2from django.shortcuts import render
3from django.conf import settings
4from ultralytics import YOLO
5from django.core.files.storage import FileSystemStorage
6
7# 加载训练好的模型(放在项目根目录)
8MODEL_PATH = os.path.join(settings.BASE_DIR, 'best.pt')
9model = YOLO(MODEL_PATH)
10
11def index(request):
12 return render(request, 'detector/index.html')
13
14def detect(request):
15 if request.method == 'POST' and request.FILES.get('image'):
16 # 1. 保存上传的图片
17 uploaded_file = request.FILES['image']
18 fs = FileSystemStorage()
19 filename = fs.save(uploaded_file.name, uploaded_file)
20 file_path = os.path.join(settings.MEDIA_ROOT, filename)
21
22 # 2. 调用YOLOv8检测
23 results = model(file_path, conf=0.5)
24
25 # 3. 保存检测结果图片
26 result_path = os.path.join(settings.MEDIA_ROOT, 'result.jpg')
27 results[0].save(filename=result_path)
28
29 # 4. 统计检测结果
30 detections = []
31 for r in results:
32 for box in r.boxes:
33 cls_id = int(box.cls)
34 conf = float(box.conf)
35 label = model.names[cls_id]
36 detections.append(f"{label} ({conf:.2f})")
37
38 return render(request, 'detector/result.html', {
39 'result_image': f'{settings.MEDIA_URL}result.jpg',
40 'detections': detections,
41 'count': len(detections)
42 })
43
44 return render(request, 'detector/index.html')
45html1<!DOCTYPE html>
2<html lang="zh-CN">
3<head>
4 <meta charset="UTF-8">
5 <title>YOLOv8 视觉检测系统</title>
6 <style>
7 body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; text-align: center; }
8 .upload-box { border: 2px dashed #ccc; padding: 40px; border-radius: 10px; margin: 20px 0; }
9 button { background: #007bff; color: white; border: none; padding: 12px 30px; font-size: 16px; border-radius: 5px; cursor: pointer; }
10 button:hover { background: #0056b3; }
11 img { max-width: 100%; margin-top: 20px; border-radius: 8px; }
12 </style>
13</head>
14<body>
15 <h1>🎯 YOLOv8 视觉检测系统</h1>
16 <p>上传一张图片,AI 帮你识别图中的目标</p>
17
18 <form method="post" enctype="multipart/form-data" class="upload-box">
19 {% csrf_token %}
20 <input type="file" name="image" accept="image/*" required>
21 <br><br>
22 <button type="submit">🔍 开始检测</button>
23 </form>
24</body>
25</html>
26html1<!DOCTYPE html>
2<html lang="zh-CN">
3<head>
4 <meta charset="UTF-8">
5 <title>检测结果</title>
6 <style>
7 body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; text-align: center; }
8 img { max-width: 100%; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
9 .info { background: #f0f8ff; padding: 20px; border-radius: 10px; margin: 20px 0; }
10 .back { display: inline-block; margin-top: 20px; color: #007bff; text-decoration: none; }
11 </style>
12</head>
13<body>
14 <h1>✅ 检测完成!共发现 {{ count }} 个目标</h1>
15
16 <img src="{{ result_image }}" alt="检测结果">
17
18 <div class="info">
19 <h3>📋 检测详情:</h3>
20 {% for d in detections %}
21 <p>{{ d }}</p>
22 {% endfor %}
23 </div>
24
25 <a href="/" class="back">← 返回首页继续检测</a>
26</body>
27</html>
28detector/urls.py:
python1from django.urls import path
2from . import views
3
4urlpatterns = [
5 path('', views.index, name='index'),
6 path('detect/', views.detect, name='detect'),
7]
8修改 index.html 中的 form action:
html1<form method="post" enctype="multipart/form-data" class="upload-box" action="{% url 'detector:detect' %}">
2bash1python manage.py runserver
2访问 http://127.0.0.1:8000/ → 上传图片 → 点击检测 → 0.03秒后,检测结果扑面而来! 🎉🎉🎉
python1from moviepy.editor import VideoFileClip
2
3def detect_video(request):
4 if request.method == 'POST' and request.FILES.get('video'):
5 video_path = os.path.join(settings.MEDIA_ROOT, request.FILES['video'].name)
6 output_path = os.path.join(settings.MEDIA_ROOT, 'output.mp4')
7
8 clip = VideoFileClip(video_path)
9
10 def process_frame(frame):
11 results = model(frame, conf=0.5, verbose=False)
12 return results[0].plot()
13
14 modified_clip = clip.fl_image(process_frame)
15 modified_clip.write_videofile(output_path, codec='libx264')
16
17 return render(request, 'detector/result.html', {
18 'result_image': f'{settings.MEDIA_URL}output.mp4',
19 'detections': ['视频检测完成'],
20 'count': 1
21 })
22天数 | 阶段 | 核心任务 | 里程碑 |
|---|---|---|---|
Day 1~2 | 环境搭建 | Conda + PyTorch + YOLOv8 + Django + LabelImg | ✅ 全部环境就绪 |
Day 3~4 | YOLOv8入门 | 跑通官方示例 + 标注自己的数据集 | ✅ 能用预训练模型检测 |
Day 5~7 | 模型训练 | 训练自己的YOLOv8模型 + 调参优化 | ✅ 拥有自己的best.pt |
Day 8~9 | Django基础 | 项目搭建 + 页面路由 + 静态文件 | ✅ 网站能跑 |
Day 10~11 | 核心集成 | Django接收图片 → YOLOv8检测 → 返回结果 | ✅ 上传图片能出结果 |
Day 12~13 | 进阶功能 | 视频检测 + 批量处理 + 结果统计 | ✅ 功能完整 |
Day 14 | 部署上线 | Docker打包 / 云服务器部署 | ✅ 真正能给别人用 |
坑 | 症状 | 解决方案 |
|---|---|---|
🔥 CUDA OOM | RuntimeError: CUDA out of memory | 减小batch、imgsz,或用梯度累积 accum=2 |
🔥 DataLoader报错 | worker exited unexpectedly | 设置 workers=0 或 workers=2,升级Pillow |
🔥 ONNX导出失败 | AttributeError: 'NoneType' | 升级onnx:pip install --upgrade onnx onnxruntime |
🔥 中文路径报错 | 各种莫名其妙的错误 | 所有路径、文件名必须用英文! |
🔥 端口被占用 | Error: That port is already in use | 换个端口:python manage.py runserver 8080 |
🔥 conda init报错 | Run 'conda init' before 'conda activate' | 管理员PowerShell执行:Set-ExecutionPolicy RemoteSigned -Scope CurrentUser |
Django给了你一个网站,YOLOv8给了这个网站一双眼睛。而你,是那个让它们协同工作的人。
这不是两个独立的技术,而是一套完整的全栈视觉解决方案。学会它,你能做的事情远超想象:
应用场景 | 技术实现 |
|---|---|
🏭 工业质检 | 上传产品图 → 检测缺陷 → 自动打回 |
🚗 交通监控 | 上传监控截图 → 识别车辆/行人 → 统计流量 |
📚 课堂行为分析 | 上传课堂视频 → 检测举手/趴桌 → 生成热力图 |
🔒 安防系统 | 上传抓拍图 → 人脸检测 → 实时告警 |
支柱 | 一句话 |
|---|---|
🏗️ Django | Web骨架,处理请求、管理数据、返回页面 |
🏗️ YOLOv8 | AI之眼,35ms内看懂图片里有什么 |
🏗️ 集成 | 上传 → 检测 → 返回,三步打通全链路 |
🏗️ 部署 | Docker一键打包,云服务器随时上线 |
别人还在纠结"学Python还是学Java"的时候,你已经用Django+YOLOv8做出了一个能看、能想、能干活的全栈视觉系统。
现在,打开终端,输入:
bash1conda create -n yolov8_env python=3.8 -y
2conda activate yolov8_env
3pip install ultralytics django -i https://pypi.tuna.tsinghua.edu.cn/simple
4你的视觉开发之路,从这一行命令开始。🚀
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。