Java+MySQL实战 智能垃圾分类督导系统(图像识别+积分奖励机制)
·
Java+MySQL实战:智能垃圾分类督导系统(图像识别+积分奖励机制)
下面我将详细介绍一个基于Java和MySQL的智能垃圾分类督导系统的完整设计方案,包含图像识别功能和积分奖励机制。
一、系统架构设计
1. 技术栈
- 前端:JavaFX/Spring Boot + Thymeleaf 或 Vue.js
- 后端:Spring Boot + Spring MVC + Spring Security
- 图像识别:OpenCV + TensorFlow/PyTorch(Java调用Python服务)
- 数据库:MySQL 8.0
- 其他:Redis(缓存)、RabbitMQ(消息队列)
2. 系统模块
智能垃圾分类督导系统
├── 用户管理模块
├── 垃圾分类识别模块
├── 积分管理模块
├── 数据统计模块
├── 消息通知模块
└── 系统管理模块
二、数据库设计
1. 主要表结构
用户表(users)
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL,
real_name VARCHAR(50),
phone VARCHAR(20),
email VARCHAR(100),
avatar VARCHAR(255),
total_points INT DEFAULT 0,
level INT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
垃圾分类表(garbage_categories)
CREATE TABLE garbage_categories (
category_id INT AUTO_INCREMENT PRIMARY KEY,
category_name VARCHAR(50) NOT NULL UNIQUE,
description TEXT,
icon VARCHAR(255)
);
垃圾投放记录表(disposal_records)
CREATE TABLE disposal_records (
record_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
category_id INT NOT NULL,
image_path VARCHAR(255) NOT NULL,
weight DECIMAL(10,2),
points_earned INT NOT NULL,
disposal_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (category_id) REFERENCES garbage_categories(category_id)
);
积分记录表(point_records)
CREATE TABLE point_records (
record_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
points_change INT NOT NULL,
change_type ENUM('disposal', 'exchange', 'admin', 'other'),
related_id INT,
description VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
三、核心功能实现
1. 图像识别模块
Java调用Python图像识别服务
// Python服务调用示例
public class ImageRecognitionService {
private static final String PYTHON_SERVICE_URL = "http://localhost:5000/recognize";
public String recognizeGarbage(MultipartFile imageFile) {
try {
// 构建请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("image", new ByteArrayResource(imageFile.getBytes()) {
@Override
public String getFilename() {
return imageFile.getOriginalFilename();
}
});
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
// 发送请求
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(
PYTHON_SERVICE_URL, requestEntity, String.class);
return response.getBody();
} catch (Exception e) {
throw new RuntimeException("图像识别服务调用失败", e);
}
}
}
Python图像识别服务(Flask实现)
from flask import Flask, request, jsonify
import cv2
import numpy as np
from tensorflow.keras.models import load_model
app = Flask(__name__)
model = load_model('garbage_classifier.h5')
categories = ['可回收物', '有害垃圾', '厨余垃圾', '其他垃圾']
@app.route('/recognize', methods=['POST'])
def recognize():
if 'image' not in request.files:
return jsonify({'error': 'No image provided'}), 400
file = request.files['image']
img = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
img = cv2.resize(img, (224, 224))
img = img / 255.0
img = np.expand_dims(img, axis=0)
pred = model.predict(img)
category_idx = np.argmax(pred)
return jsonify({
'category': categories[category_idx],
'confidence': float(pred[0][category_idx])
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
2. 积分奖励机制
积分计算服务
@Service
public class PointService {
@Autowired
private PointRecordRepository pointRecordRepository;
@Autowired
private GarbageCategoryRepository categoryRepository;
@Transactional
public void awardPoints(User user, GarbageCategory category, Double weight) {
// 计算基础积分
int basePoints = category.getBasePoints();
int additionalPoints = (int) (weight * category.getPointsPerKg());
int totalPoints = basePoints + additionalPoints;
// 更新用户总积分
user.setTotalPoints(user.getTotalPoints() + totalPoints);
// 记录积分变化
PointRecord record = new PointRecord();
record.setUser(user);
record.setPointsChange(totalPoints);
record.setChangeType(PointChangeType.DISPOSAL);
record.setDescription("垃圾分类投放奖励");
pointRecordRepository.save(record);
}
// 其他积分操作方法...
}
积分兑换商品
@RestController
@RequestMapping("/api/points")
public class PointController {
@Autowired
private PointService pointService;
@PostMapping("/exchange")
public ResponseEntity<?> exchangePoints(@RequestBody ExchangeRequest request) {
try {
pointService.exchangePoints(request.getUserId(), request.getItemId());
return ResponseEntity.ok("兑换成功");
} catch (InsufficientPointsException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
// 其他积分相关API...
}
3. 垃圾分类记录处理
@Service
public class DisposalService {
@Autowired
private DisposalRecordRepository recordRepository;
@Autowired
private ImageRecognitionService recognitionService;
@Autowired
private PointService pointService;
@Transactional
public DisposalRecord processDisposal(MultipartFile imageFile, User user) {
// 1. 图像识别
String categoryName = recognitionService.recognizeGarbage(imageFile);
GarbageCategory category = categoryRepository.findByName(categoryName)
.orElseThrow(() -> new RuntimeException("未知垃圾类别"));
// 2. 保存记录
DisposalRecord record = new DisposalRecord();
record.setUser(user);
record.setCategory(category);
record.setImagePath(saveImage(imageFile));
record.setStatus(DisposalStatus.PENDING);
// 3. 管理员审核后发放积分
// 实际项目中可以通过消息队列异步处理
if (autoApproveEnabled()) {
approveRecord(record);
}
return recordRepository.save(record);
}
private void approveRecord(DisposalRecord record) {
record.setStatus(DisposalStatus.APPROVED);
pointService.awardPoints(record.getUser(), record.getCategory(), record.getWeight());
recordRepository.save(record);
// 发送通知
notificationService.sendDisposalApproved(record.getUser(), record);
}
}
四、系统特色功能
1. 智能识别优化
- 支持多物品识别,给出混合垃圾的分类建议
- 识别置信度低于阈值时自动转人工审核
- 用户反馈机制优化模型
2. 积分激励机制
- 每日首次分类奖励翻倍
- 连续打卡额外奖励
- 积分排行榜和等级系统
- 积分兑换实物商品或优惠券
3. 数据可视化
@RestController
@RequestMapping("/api/stats")
public class StatisticsController {
@Autowired
private DisposalRecordRepository recordRepository;
@GetMapping("/user/{userId}")
public UserStats getUserStats(@PathVariable Long userId) {
UserStats stats = new UserStats();
// 分类统计
stats.setCategoryStats(recordRepository.countByUserGroupByCategory(userId));
// 时间趋势
stats.setWeeklyTrend(recordRepository.countLastWeekDaily(userId));
// 积分变化
stats.setPointHistory(pointService.getPointHistory(userId));
return stats;
}
@GetMapping("/community")
public CommunityStats getCommunityStats() {
// 社区分类数据、排名等
}
}
五、部署方案
1. 开发环境
- JDK 11+
- MySQL 8.0
- Python 3.7+ (图像识别服务)
- Redis (缓存和会话管理)
2. 生产环境部署
# docker-compose.yml 示例
version: '3'
services:
app:
build: .
ports:
- "8080:8080"
depends_on:
- db
- redis
- python-service
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/garbage_db
SPRING_REDIS_HOST: redis
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: rootpass
MYSQL_DATABASE: garbage_db
MYSQL_USER: appuser
MYSQL_PASSWORD: apppass
volumes:
- db_data:/var/lib/mysql
redis:
image: redis:alpine
python-service:
build: ./python-service
ports:
- "5000:5000"
volumes:
- ./python-service/models:/app/models
volumes:
db_data:
六、扩展方向
- 移动端应用:开发配套App,支持扫码识别和定位投放点
- 社区功能:添加垃圾分类知识分享和问答社区
- IoT集成:连接智能垃圾桶,自动称重和识别
- 区块链技术:积分上链,实现跨平台流通
- 大数据分析:垃圾投放行为分析和区域垃圾产生预测
这个系统通过图像识别技术简化了垃圾分类流程,结合积分奖励机制激励用户参与,实现了垃圾分类的智能化管理和正向引导。
更多推荐
所有评论(0)