如何使用深度学习目标检测算法Yolo训练非机动车头盔佩戴检测_电动车头盔佩戴数据集,来构建基于深度学习卷积神经网络的YOLOv8+Pyqt5的电动车头盔佩戴检测系统
以下文字及代码仅供参考。
基于YOLOv8+PyQt5的电动车头盔佩戴检测算法
yolov8的优势:
实验表明:
YOLOv8在小目标检测方面展现了明显优势,不仅提高了检测速度,也增强了检测效果,有助于提升电动车头盔佩戴检测效率,为交通系统提供更迅速、更可靠的服务。
该算法能够在实时性和准确性方面达到较高的水平。
实验表明:
YOLOv8在小目标检测方面展现了明显优势,不仅提高了检测速度,也增强了检测效果,有助于提升电动车头盔佩戴检测效率,为交通系统提供更迅速、更可靠的服务。
三类别:数据集:1164张图片用于训练,299张图片用于验证。其中检测的类别包含电动车及摩托车(two_wheeler)、佩戴头盔(helmet)和未佩戴头盔(without)三类。
1界面效果
构建基于YOLOv8和PyQt5的电动车头盔佩戴检测系统是一个综合性的项目,涉及数据准备、模型训练、推理以及GUI设计等多个环节。以下是详细的步骤和代码示例。
1. 环境搭建
确保安装了必要的库:
pip install ultralytics opencv-python PyQt5 numpy pandas
2. 数据准备
2.1 数据集格式转换
假设你已经有了标注好的数据集,需要将其转换为YOLOv8支持的格式(即标签文件为.txt
,内容为<class> <x_center> <y_center> <width> <height>
)。
import os
import xml.etree.ElementTree as ET
def convert_annotation(xml_file, img_size, class_map):
tree = ET.parse(xml_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
bboxes = []
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in class_map:
continue
cls_id = class_map[cls]
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),
float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
bb = convert_bbox((w, h), b)
bboxes.append([cls_id] + list(bb))
return bboxes
def convert_bbox(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = (box[0] + box[1])/2.0 - 1
y = (box[2] + box[3])/2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x*dw
w = w*dw
y = y*dh
h = h*dh
return (x, y, w, h)
# 示例:将VOC格式转换为YOLO格式
data_dir = 'path/to/dataset'
class_map = {'two_wheeler': 0, 'helmet': 1, 'without': 2}
for filename in os.listdir(os.path.join(data_dir, 'Annotations')):
if filename.endswith('.xml'):
xml_path = os.path.join(data_dir, 'Annotations', filename)
img_path = os.path.join(data_dir, 'JPEGImages', filename.replace('.xml', '.jpg'))
img = cv2.imread(img_path)
h, w, _ = img.shape
bboxes = convert_annotation(xml_path, (w, h), class_map)
with open(os.path.join(data_dir, 'labels', filename.replace('.xml', '.txt')), 'w') as f:
for bbox in bboxes:
f.write(' '.join(str(x) for x in bbox) + '\n')
2.2 数据划分
将数据集划分为训练集和验证集:
from sklearn.model_selection import train_test_split
train_ratio = 0.8
val_ratio = 0.2
image_files = [f for f in os.listdir(os.path.join(data_dir, 'images')) if f.endswith('.jpg')]
train_files, val_files = train_test_split(image_files, test_size=val_ratio, random_state=42)
with open(os.path.join(data_dir, 'train.txt'), 'w') as f:
for file in train_files:
f.write(os.path.join(data_dir, 'images', file) + '\n')
with open(os.path.join(data_dir, 'val.txt'), 'w') as f:
for file in val_files:
f.write(os.path.join(data_dir, 'images', file) + '\n')
3. 模型训练
使用YOLOv8进行模型训练:
from ultralytics import YOLO
model = YOLO('yolov8s.yaml') # 使用小规模模型作为起点
model.train(data='path/to/data.yaml', epochs=100, batch=16, workers=4)
# data.yaml示例:
# train: path/to/train.txt
# val: path/to/val.txt
# nc: 3
# names: ['two_wheeler', 'helmet', 'without']
4. 模型推理
编写推理代码:
import cv2
from ultralytics import YOLO
model = YOLO('path/to/best.pt')
def detect_helmet(image_path):
results = model(image_path)
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0])
label = model.names[int(box.cls)]
confidence = round(float(box.conf), 2)
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f'{label} {confidence}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
return image
image = cv2.imread('path/to/image.jpg')
detected_image = detect_helmet(image)
cv2.imshow('Detected Image', detected_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
5. GUI设计
使用PyQt5创建交互式界面:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel, QFileDialog
from PyQt5.QtGui import QPixmap
import cv2
from ultralytics import YOLO
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = '头盔佩戴检测系统'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.load_button = QPushButton('选择图片', self)
self.load_button.move(50, 50)
self.load_button.clicked.connect(self.load_image)
self.detect_button = QPushButton('检测头盔', self)
self.detect_button.move(150, 50)
self.detect_button.clicked.connect(self.detect_helmet)
self.image_label = QLabel(self)
self.image_label.move(50, 100)
self.show()
def load_image(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "", "Images (*.png *.xpm *.jpg)", options=options)
if file_name:
pixmap = QPixmap(file_name)
self.image_label.setPixmap(pixmap)
self.image_path = file_name
def detect_helmet(self):
model = YOLO('path/to/best.pt')
image = cv2.imread(self.image_path)
results = model(image)
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0])
label = model.names[int(box.cls)]
confidence = round(float(box.conf), 2)
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f'{label} {confidence}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
height, width, channel = image.shape
bytes_per_line = 3 * width
q_img = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(q_img)
self.image_label.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
通过上述步骤同学
可以构建一个完整的基于YOLOv8和PyQt5的电动车头盔佩戴检测系统,并通过图形用户界面提供便捷的操作体验。
所有这个仅供参考。方便交流学习。