
利用深度学习目标检测算法通用Yolov5训练电动车进电梯数据集 建立基于YOLOv5的电动车入梯识别系统 识别检测电梯进电动车的预警识别文章目录1. 数据准备标注工具2. 模型训练安装YOLOv5准备配置文件训练模型3. UI设计安装PyQt5创建主窗口4. 数据库集成数据库管理 (db_utils.py)5. 实时检测总结基于YOLOv5的电动车入梯识别系统1构建一个基于YOLOv5s的电动车入梯识别系统我们需要完成以下几个步骤数据准备收集和标注数据集。模型训练使用YOLOv5进行模型训练。UI设计使用PyQt5设计用户界面。数据库集成使用MySQL存储检测结果。实时检测集成模型到UI中实现实时检测。1. 数据准备首先你需要一个包含电动车的数据集。你可以从公开数据集中获取或者自己采集并标注数据。标注工具使用LabelImg等工具进行数据标注。2. 模型训练安装YOLOv5gitclone https://github.com/ultralytics/yolov5.gitcdyolov5 pipinstall-rrequirements.txt准备配置文件在yolov5目录下创建data.yamltrain:./images/trainval:./images/valtest:./images/testnc:1# number of classesnames:[electric_bicycle]训练模型python train.py--img640--batch16--epochs100--datadata.yaml--cfgcfg/training/yolov5s.yaml--weightsyolov5s.pt--nameyolov5s_results3. UI设计使用PyQt5设计用户界面。安装PyQt5pipinstallPyQt5创建主窗口importsysfromPyQt5.QtWidgetsimportQApplication,QMainWindow,QLabel,QPushButton,QVBoxLayout,QWidget,QFileDialog,QMessageBox,QTableWidget,QTableWidgetItemfromPyQt5.QtGuiimportQPixmap,QImagefromPyQt5.QtCoreimportQTimerimportcv2importnumpyasnpfromultralyticsimportYOLOimportmysql.connectorclassElectricBikeDetection(QMainWindow):def__init__(self):super().__init__()self.initUI()self.modelYOLO(best.pt)# 加载训练好的模型self.dbDatabaseManager(localhost,root,password,detection_db)definitUI(self):self.setWindowTitle(电动车入梯识别系统)self.setGeometry(100,100,800,600)self.labelQLabel(self)self.label.setText(请选择视频文件或打开摄像头)self.label.setAlignment(Qt.AlignCenter)self.button_loadQPushButton(选择文件,self)self.button_load.clicked.connect(self.load_video)self.button_startQPushButton(开始识别,self)self.button_start.clicked.connect(self.start_detection)self.button_cameraQPushButton(打开摄像头,self)self.button_camera.clicked.connect(self.open_camera)self.button_close_cameraQPushButton(关闭摄像头,self)self.button_close_camera.clicked.connect(self.close_camera)self.tableQTableWidget(self)self.table.setColumnCount(4)self.table.setHorizontalHeaderLabels([时间,位置,置信度,图片])layoutQVBoxLayout()layout.addWidget(self.label)layout.addWidget(self.button_load)layout.addWidget(self.button_start)layout.addWidget(self.button_camera)layout.addWidget(self.button_close_camera)layout.addWidget(self.table)containerQWidget()container.setLayout(layout)self.setCentralWidget(container)self.capNoneself.timerNonedefload_video(self):optionsQFileDialog.Options()file_name,_QFileDialog.getOpenFileName(self,选择视频文件,,Video Files (*.mp4 *.avi),optionsoptions)iffile_name:self.video_pathfile_name self.capcv2.VideoCapture(file_name)self.timerQTimer(self)self.timer.timeout.connect(self.update_frame)self.timer.start(30)# 每秒更新30帧defstart_detection(self):ifnothasattr(self,video_path):QMessageBox.warning(self,警告,请先选择视频文件)returnself.button_start.setEnabled(False)self.detect_electric_bikes()defdetect_electric_bikes(self):whileself.cap.isOpened():ret,frameself.cap.read()ifnotret:breakresultsself.model(frame)annotated_frameresults[0].plot()height,width,channelannotated_frame.shape bytes_per_line3*width q_imgQImage(annotated_frame.data,width,height,bytes_per_line,QImage.Format_RGB888).rgbSwapped()self.label.setPixmap(QPixmap.fromImage(q_img))forresultinresults:boxesresult.boxes.xyxy.cpu().numpy()confidencesresult.boxes.conf.cpu().numpy()classesresult.boxes.cls.cpu().numpy()forbox,conf,clsinzip(boxes,confidences,classes):x_min,y_min,x_max,y_maxmap(int,box)confidenceconf.item()self.db.insert_detection(x_min,y_min,x_max,y_max,confidence)self.update_table()self.app.processEvents()# 更新UIdefupdate_frame(self):ret,frameself.cap.read()ifnotret:self.timer.stop()self.cap.release()self.button_start.setEnabled(True)returnresultsself.model(frame)annotated_frameresults[0].plot()height,width,channelannotated_frame.shape bytes_per_line3*width q_imgQImage(annotated_frame.data,width,height,bytes_per_line,QImage.Format_RGB888).rgbSwapped()self.label.setPixmap(QPixmap.fromImage(q_img))defopen_camera(self):self.capcv2.VideoCapture(0)self.timerQTimer(self)self.timer.timeout.connect(self.update_frame)self.timer.start(30)# 每秒更新30帧defclose_camera(self):ifself.capisnotNone:self.timer.stop()self.cap.release()self.capNonedefupdate_table(self):detectionsself.db.get_all_detections()self.table.clearContents()self.table.setRowCount(len(detections))fori,detectioninenumerate(detections):timedetection[time]positionf({detection[x_min]},{detection[y_min]},{detection[x_max]},{detection[y_max]})confidencedetection[confidence]image_pathdetection[image_path]self.table.setItem(i,0,QTableWidgetItem(time))self.table.setItem(i,1,QTableWidgetItem(position))self.table.setItem(i,2,QTableWidgetItem(f{confidence:.2f}))self.table.setItem(i,3,QTableWidgetItem(image_path))if__name____main__:appQApplication(sys.argv)windowElectricBikeDetection()window.show()sys.exit(app.exec_())4. 数据库集成使用MySQL存储检测结果。数据库管理 (db_utils.py)importmysql.connectorclassDatabaseManager:def__init__(self,host,user,password,db_name):self.connmysql.connector.connect(hosthost,useruser,passwordpassword,databasedb_name)self.create_tables()defcreate_tables(self):cursorself.conn.cursor()cursor.execute( CREATE TABLE IF NOT EXISTS detections ( id INT AUTO_INCREMENT PRIMARY KEY, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, x_min INT, y_min INT, x_max INT, y_max INT, confidence FLOAT, image_path VARCHAR(255) ) )self.conn.commit()definsert_detection(self,x_min,y_min,x_max,y_max,confidence,image_pathNone):cursorself.conn.cursor()cursor.execute( INSERT INTO detections (x_min, y_min, x_max, y_max, confidence, image_path) VALUES (?, ?, ?, ?, ?, ?) ,(x_min,y_min,x_max,y_max,confidence,image_path))self.conn.commit()defget_all_detections(self):cursorself.conn.cursor()cursor.execute(SELECT * FROM detections)returncursor.fetchall()defclose(self):self.conn.close()5. 实时检测在上述代码中我们实现了以下功能选择视频文件。开始识别按钮触发检测过程。打开和关闭摄像头。实时显示检测结果。将检测结果存储到MySQL数据库中。总结仅供参考同学构建一个基于YOLOv5s的电动车入梯识别系统。这个系统包括数据准备、模型训练、UI设计、数据库集成和实时检测等功能。