基于深度学习的景区垃圾识别系统(UI界面+YOLOv8/v7/v6/v5代码+训练数据集)
1. 引言
景区垃圾识别是环保管理的重要任务之一。传统的人工清理方式效率低、成本高,而借助深度学习技术可以实现自动化的垃圾检测与识别,提高景区的清洁度和管理效率。
2. 项目准备
必备环境与工具
- Python:项目开发的主要编程语言
- Anaconda:Python数据科学平台,便于环境管理和包管理
- YOLO (You Only Look Once):目标检测模型,选择v8/v7/v6/v5版本
- OpenCV:计算机视觉库
- Flask/Django:用于搭建UI界面的Web框架
安装与配置步骤
- 安装Python与Anaconda
从Python官网下载安装Python:https://www.python.org/downloads/
从Anaconda官网下载安装Anaconda:https://www.anaconda.com/products/distribution - 配置YOLO环境
安装YOLO依赖:
pip install torch torchvision torchaudio
pip install -U git+https://github.com/ultralytics/yolov5
3. 数据集准备
数据集简介
使用公开的垃圾检测数据集,包含景区多种场景的垃圾图像和标注。
数据集下载链接:https://www.kaggle.com/datasets
数据预处理
- 数据增强与标注
使用LabelImg进行图像标注:https://github.com/tzutalin/labelImg
安装LabelImg:
pip install labelImg
运行LabelImg进行图像标注:
labelImg
- 数据集划分
将数据集划分为训练集、验证集和测试集:
import os
import shutil
import random
def split_dataset(source_dir, train_dir, val_dir, test_dir, train_ratio=0.7, val_ratio=0.2):
all_files = os.listdir(source_dir)
random.shuffle(all_files)
train_count = int(len(all_files) * train_ratio)
val_count = int(len(all_files) * val_ratio)
for i, file in enumerate(all_files):
if i < train_count:
shutil.move(os.path.join(source_dir, file), train_dir)
elif i < train_count + val_count:
shutil.move(os.path.join(source_dir, file), val_dir)
else:
shutil.move(os.path.join(source_dir, file), test_dir)
split_dataset('data/source', 'data/train', 'data/val', 'data/test')
4. 模型训练
YOLO模型简介
YOLO (You Only Look Once) 是一种快速准确的目标检测模型。YOLOv8/v7/v6/v5 是不同版本的YOLO模型,性能和速度有所不同。
配置与训练
- 配置文件的修改
修改YOLO配置文件:
# example.yaml
train: data/train
val: data/val
nc: 1 # number of classes (garbage)
names: ['garbage']
- 超参数调整
在配置文件中调整超参数,如batch size、learning rate等。 - 训练模型的步骤
使用以下命令训练模型:
python train.py --img 640 --batch 16 --epochs 50 --data example.yaml --cfg yolov5s.yaml --weights yolov5s.pt
训练过程中的常见问题与解决
- 内存不足:减少batch size
- 训练速度慢:使用GPU加速,确保CUDA正确安装
5. 模型评估与优化
模型评估指标
- 准确率 (Accuracy)
- 召回率 (Recall)
- F1分数 (F1 Score)
from sklearn.metrics import accuracy_score, recall_score, f1_score
y_true = [...] # true labels
y_pred = [...] # predicted labels
accuracy = accuracy_score(y_true, y_pred)
recall = recall_score(y_true, y_pred, average='macro')
f1 = f1_score(y_true, y_pred, average='macro')
print(f"Accuracy: {accuracy}, Recall: {recall}, F1 Score: {f1}")
模型优化策略
- 数据增强:使用更多的数据增强技术,如旋转、缩放、裁剪等
- 超参数调优:通过网格搜索或贝叶斯优化找到最佳超参数
- 使用迁移学习:使用预训练模型进行微调
6. 模型部署
Flask/Django搭建UI界面
- 项目结构介绍
garbage_detection/
├── app.py
├── templates/
│ ├── index.html
│ └── result.html
├── static/
│ └── styles.css
└── models/
└── yolov5s.pt
- 创建基础的网页模板
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Garbage Detection</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Garbage Detection</h1>
<form action="/predict" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
</body>
</html>
- result.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Result</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Detection Result</h1>
<img src="{{ url_for('static', filename='uploads/' + filename) }}" alt="Uploaded Image">
<p>{{ result }}</p>
</body>
</html>
后端集成
- 接口设计与实现
- app.py
from flask import Flask, request, render_template, url_for
import os
from werkzeug.utils import secure_filename
import torch
from PIL import Image
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
model = torch.hub.load('ultralytics/yolov5', 'custom', path='models/yolov5s.pt')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
if file:
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
img = Image.open(filepath)
results = model(img)
results.save(save_dir=app.config['UPLOAD_FOLDER'])
return render_template('result.html', filename=filename, result=results.pandas().xyxy[0].to_json(orient="records"))
if __name__ == '__main__':
app.run(debug=True)
部署模型到服务器
- 使用Gunicorn或其他部署工具
pip install gunicorn
gunicorn -w 4 app:app
- 部署到云服务器
以AWS为例,创建EC2实例,配置安全组,上传项目文件,并使用Gunicorn运行应用。
7. 系统测试与演示
本地测试
- 测试用例设计
设计多种景区场景测试系统的准确性。 - 测试结果分析
记录测试结果,分析模型的准确性和误差。
在线演示
- 系统演示视频
使用录屏软件录制系统的操作流程。 - 在线测试链接
部署到云服务器后,提供在线测试链接供用户体验。