基于Python的安全帽检测系统代码
时间: 2024-05-07 15:01:31 浏览: 11
以下是一个基于Python的安全帽检测系统代码,使用了OpenCV和TensorFlow等库:
```
import cv2
import numpy as np
import tensorflow as tf
# 加载模型
model = tf.keras.models.load_model('model.h5')
# 安全帽分类标签
labels = ['no_hat', 'hat']
# 加载视频流
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
# 调整图像大小
frame = cv2.resize(frame, (224, 224))
# 转换为RGB格式
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 图像预处理
frame_processed = tf.keras.applications.mobilenet_v2.preprocess_input(frame_rgb)
# 扩展维度
frame_processed = np.expand_dims(frame_processed, axis=0)
# 预测
prediction = model.predict(frame_processed)
# 获取分类结果
predicted_class = labels[np.argmax(prediction)]
# 显示结果
cv2.putText(frame, predicted_class, (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# 实时显示
cv2.imshow('Safety helmet detection', frame)
# 按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
注意,该代码需要使用已经训练好的模型文件(model.h5)以及包含安全帽分类标签的列表(labels)。在实际使用中,需要先训练模型并保存模型文件,同时也需要准备好训练数据集和测试数据集。