yolov5检测抽烟django
时间: 2025-06-29 20:18:48 浏览: 4
### 集成YOLOv5到Django项目中进行抽烟行为检测
#### 准备工作
为了在 Django 项目中集成 YOLOv5 进行抽烟行为检测,需先安装必要的依赖项。确保 Python 版本为 3.7 或以上,并已安装 PyTorch 和其他所需库。
```bash
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
pip install opencv-python matplotlib numpy
```
#### 安装YOLOv5
下载官方的 YOLOv5 GitHub 仓库并将其作为子模块添加至 Django 项目的 `apps` 文件夹下:
```bash
cd your_django_project/apps/
git clone https://github.com/ultralytics/yolov5.git
cd yolov5
pip install -r requirements.txt
```
#### 创建Django应用
创建一个新的 Django 应用来处理图像上传和检测逻辑:
```bash
python manage.py startapp smoke_detection
```
#### 修改settings.py配置
编辑 `your_django_project/settings.py` 添加新应用到 INSTALLED_APPS 列表内:
```python
INSTALLED_APPS = [
...
'smoke_detection',
]
```
#### 编写视图函数
编写用于接收图片请求、调用 YOLOv5 模型执行预测并将结果显示给用户的视图函数,在 `smoke_detection/views.py` 中加入如下代码片段:
```python
from django.shortcuts import render, redirect
from .forms import ImageForm
import cv2
from pathlib import Path
from PIL import Image as pil_image
import os
import torch
from django.conf import settings
def detect_smoking(request):
form = ImageForm()
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
image_instance = form.save(commit=False)
# Load model only once at startup or use a global variable to store it.
weights_path = str(Path(settings.BASE_DIR).joinpath('yolov5', 'runs', 'train', 'exp', 'weights', 'best.pt'))
model = torch.hub.load(str(Path(settings.BASE_DIR).joinpath('yolov5')), 'custom', path=weights_path, source='local')
img = pil_image.open(image_instance.image.path)
results = model(img)
result_img = results.render()[0]
output_filename = f"{Path(image_instance.image.name).stem}_result.jpg"
output_filepath = Path(settings.MEDIA_ROOT) / output_filename
cv2.imwrite(str(output_filepath), cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR))
context = {
'form': form,
'image_url': image_instance.image.url,
'output_image_url': f"/media/{output_filename}"
}
return render(request, 'detection.html', context=context)
context = {'form': form}
return render(request, 'upload.html', context=context)
```
上述代码实现了从用户处获取待测图片文件,利用预训练好的 YOLOv5 模型对其进行分析,并返回带有标注框的结果图片[^1]。
#### 设计模板页面
设计两个 HTML 页面分别负责显示上传表单 (`templates/upload.html`) 及展示检测结果 (`templates/detection.html`)。
##### upload.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload an Image</title>
</head>
<body>
<h2>Select an image with smoking behavior:</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Detect Smoking Behavior</button>
</form>
</body>
</html>
```
##### detection.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Detect Result</title>
</head>
<body>
<h2>Your uploaded image is below.</h2>
<img src="{{ image_url }}" alt="Uploaded Image"/>
<br/>
<h2>The detected result of the image is shown hereafter.</h2>
<img src="{{ output_image_url }}" alt="Detected Result"/>
<a href="{% url 'detect' %}">Back To Upload Page</a>
</body>
</html>
```
#### URL路由设置
最后一步是在 `urls.py` 设置好对应的URL映射关系以便访问相应的视图方法:
```python
from django.urls import path
from .views import detect_smoking
urlpatterns = [
path('', detect_smoking, name='detect'),
]
```
完成这些操作之后就可以启动服务器测试整个流程了。当一切正常运行时,应该可以在浏览器里看到一个简单的网页允许上传一张照片来查看是否存在吸烟行为被标记出来。
阅读全文
相关推荐


















