实现一个车牌识别系统,使用YOLOv5和YOLOv7这两种不同的模型来进行车牌的检测。下面我将提供一个完整的项目概述,包括模型训练脚本、车牌识别代码以及两个GUI界面,分别用于处理静态图片和实时视频流
1. 模型训练
- YOLOv5 和 YOLOv7 的训练脚本。
- 使用车牌数据集进行训练。
2. 车牌识别
- Python 代码实现车牌的检测与识别。
- 支持多种车牌类型,例如黄色、绿色、双层车牌等。
3. GUI 界面
- 静态图片检测 GUI。
- 实时视频检测 GUI。
技术栈
- YOLOv5 和 YOLOv7: 对象检测框架。
- OpenCV: 图像处理和视频流处理。
- PyQt5: GUI 库。
- Python: 编程语言。
项目结构
yolov5
: YOLOv5 相关文件夹。yolov7
: YOLOv7 相关文件夹。gui
: GUI 文件夹。data
: 包含训练数据集和配置文件。weights
: 存放训练后的权重文件。utils
: 公共工具函数。main.py
: 主入口文件。
1. 模型训练
YOLOv5 训练脚本 (train_yolov5.py
)
1# train_yolov5.py
2
3from ultralytics import YOLO
4
5def train_yolov5():
6 model = YOLO('yolov5s.yaml') # 使用配置文件创建模型
7 model.train(data='data/plate.yaml', epochs=100, batch=16, imgsz=640)
8
9if __name__ == '__main__':
10 train_yolov5()
YOLOv7 训练脚本 (train_yolov7.py
)
1# train_yolov7.py
2
3from yolov7.train import parse_opt, run
4
5def train_yolov7():
6 opt = parse_opt(known=True)
7 opt.cfg = 'yolov7.yaml'
8 opt.data = 'data/plate.yaml'
9 opt.weights = 'yolov7.pt'
10 opt.batch_size = 16
11 opt.epochs = 100
12 opt.img_size = 640
13 run(**vars(opt))
14
15if __name__ == '__main__':
16 train_yolov7()
2. 车牌识别
Python 车牌识别脚本 (detect_plate.py
)
1# detect_plate.py
2
3import cv2
4import torch
5import numpy as np
6from ultralytics import YOLO
7
8def load_model(model_path):
9 return YOLO(model_path)
10
11def detect_plate(model, source):
12 results = model.predict(source=source, save=False, conf=0.5)
13 for result in results:
14 boxes = result.boxes
15 for box in boxes:
16 x1, y1, x2, y2 = box.xyxy[0].tolist()
17 cv2.rectangle(source, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
18 label = f'{model.model.names[int(box.cls)]} {box.conf[0]:.2f}'
19 cv2.putText(source, label, (int(x1), int(y1)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
20 return source
21
22def main():
23 model = load_model('weights/best.pt')
24 cap = cv2.VideoCapture(0) # 0 表示默认摄像头
25 while True:
26 ret, frame = cap.read()
27 if not ret:
28 break
29 frame = detect_plate(model, frame)
30 cv2.imshow('Plate Detection', frame)
31 if cv2.waitKey(1) & 0xFF == ord('q'):
32 break
33 cap.release()
34 cv2.destroyAllWindows()
35
36if __name__ == '__main__':
37 main()
3. GUI 界面
图片检测 GUI (gui_image.py
)
1# gui_image.py
2
3import sys
4from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog
5from PyQt5.QtGui import QPixmap, QImage
6import cv2
7from detect_plate import detect_plate, load_model
8
9class PlateDetectionGUI(QWidget):
10 def __init__(self):
11 super().__init__()
12 self.initUI()
13
14 def initUI(self):
15 self.setWindowTitle('License Plate Detection')
16 self.setGeometry(300, 300, 600, 400)
17
18 self.image_label = QLabel(self)
19 self.image_label.resize(400, 300)
20
21 self.load_button = QPushButton('Load Image', self)
22 self.load_button.clicked.connect(self.loadImage)
23
24 layout = QVBoxLayout()
25 layout.addWidget(self.image_label)
26 layout.addWidget(self.load_button)
27 self.setLayout(layout)
28
29 def loadImage(self):
30 options = QFileDialog.Options()
31 options |= QFileDialog.ReadOnly
32 file_name, _ = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.jpeg)", options=options)
33 if file_name:
34 image = cv2.imread(file_name)
35 image = detect_plate(load_model('weights/best.pt'), image)
36 height, width, channel = image.shape
37 bytes_per_line = 3 * width
38 q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
39 pixmap = QPixmap.fromImage(q_image)
40 self.image_label.setPixmap(pixmap)
41
42if __name__ == '__main__':
43 app = QApplication(sys.argv)
44 ex = PlateDetectionGUI()
45 ex.show()
46 sys.exit(app.exec_())
视频检测 GUI (gui_video.py
)
1# gui_video.py
2
3import sys
4from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog
5from PyQt5.QtGui import QPixmap, QImage
6from PyQt5.QtCore import QTimer
7import cv2
8from detect_plate import detect_plate, load_model
9
10class VideoDetectionGUI(QWidget):
11 def __init__(self):
12 super().__init__()
13 self.initUI()
14
15 def initUI(self):
16 self.setWindowTitle('Video License Plate Detection')
17 self.setGeometry(300, 300, 600, 400)
18
19 self.image_label = QLabel(self)
20 self.image_label.resize(400, 300)
21
22 self.load_button = QPushButton('Load Video', self)
23 self.load_button.clicked.connect(self.loadVideo)
24
25 self.start_button = QPushButton('Start Detection', self)
26 self.start_button.clicked.connect(self.start_detection)
27
28 layout = QVBoxLayout()
29 layout.addWidget(self.image_label)
30 layout.addWidget(self.load_button)
31 layout.addWidget(self.start_button)
32 self.setLayout(layout)
33
34 self.timer = QTimer(self)
35 self.timer.timeout.connect(self.update_frame)
36 self.cap = None
37
38 def loadVideo(self):
39 options = QFileDialog.Options()
40 options |= QFileDialog.ReadOnly
41 file_name, _ = QFileDialog.getOpenFileName(self, "Open Video", "", "Video Files (*.mp4 *.avi)", options=options)
42 if file_name:
43 self.cap = cv2.VideoCapture(file_name)
44
45 def start_detection(self):
46 if self.cap is not None:
47 self.timer.start(20) # 每隔20毫秒更新一帧
48
49 def update_frame(self):
50 ret, frame = self.cap.read()
51 if ret:
52 frame = detect_plate(load_model('weights/best.pt'), frame)
53 height, width, channel = frame.shape
54 bytes_per_line = 3 * width
55 q_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
56 pixmap = QPixmap.fromImage(q_image)
57 self.image_label.setPixmap(pixmap)
58
59if __name__ == '__main__':
60 app = QApplication(sys.argv)
61 ex = VideoDetectionGUI()
62 ex.show()
63 sys.exit(app.exec_())
项目注意事项
- 确保你已经安装了所有必要的库,如
ultralytics
,PyQt5
,torch
,opencv-python
等。 - 修改训练和GUI代码中的相关路径以匹配你的实际文件路径。
- 准备一个适当的车牌数据集,并根据实际情况修改训练脚本中的配置文件。
- 如果使用的是YOLOv7,请确保安装了正确的YOLOv7版本并调整训练脚本以匹配其API。
以上代码提供了从模型训练到GUI实现的完整流程。根据具体需求对这些代码进行修改和扩展。