基于深度学习的车辆轨迹识别与检测系统,对于多种车辆轨迹行为的识别检测功能:选择图片、视频识别;检测交通物体检测与实例分割 、交通轨迹识别、车辆越线计数、生成交通数据集、交通数据分析。
文章目录
-
-
- 1. 环境配置
- 2. UI设计
-
- `vehicle_trajectory.ui` 示例内容(简化版):
- 3. 主程序开发 (`main.py`)
- 4. 数据库操作示例
- 1. UI界面设计
-
- `vehicle_trajectory.ui` 示例内容:
- 2. 主程序开发
- 3. 数据库配置(可选)
-
仅供参考学习。
基于深度学习的车辆轨迹识别与检测系统

1
目标实现构建软件: 模型:YOLOV8 软件:Pycharm+Anaconda 环境:python=3.9 opencv_python PyQt5 文件: 1.完整程序文件(.py等) 2.UI界面源文件、图标(.ui、.qrc、.py等) 3.测试图片、视频文件(.jpeg、.mp4、.avi等) 
功能: 系统实现了对于多种车辆轨迹行为的识别检测功能:包括通过选择图片、视频进行实时识别;检测交通物体检测与实例分割 、交通轨迹识别、车辆越线计数、生成交通数据集、交通数据分析。
基于YOLOv8和PyQt5的车辆轨迹识别与检测系统, 是基于YOLOv8的车辆轨迹识别与目标检测系统的完整代码实现。这个系统包括了图像和视频的加载、实时检测、轨迹跟踪、车辆计数、数据集生成、数据分析等功能。 仅供参考学习。
1. 环境配置
确保安装以下依赖库:
pip install torch torchvision opencv-python PyQt5 mysql-connector-python ultralytics
2. UI设计
使用Qt Designer创建UI文件vehicle_trajectory.ui,然后转换为Python代码vehicle_trajectory_ui.py。
vehicle_trajectory.ui 示例内容(简化版):
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1200</width>
<height>800</height>
</rect>
</property>
<property name="windowTitle">
<string>基于YOLOv8的车辆轨迹识别与目标检测研究分析</string>
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QVBoxLayout" name="verticalLayout">
<!– 添加你的按钮、标签、输入框等控件 –>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
转换命令:
pyuic5 vehicle_trajectory.ui -o vehicle_trajectory_ui.py
3. 主程序开发 (main.py)
import sys
import os
import cv2
import numpy as np
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QLabel, QPushButton, QVBoxLayout, QWidget, QSlider, QLineEdit
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt
from vehicle_trajectory_ui import Ui_MainWindow
from ultralytics import YOLO
import mysql.connector
class VehicleTrajectoryApp(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# 初始化模型
self.model = YOLO('runs/detect/exp/weights/best.pt') # 替换为你的模型路径
# 连接数据库
self.db_connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
# 设置默认参数
self.confidence_threshold = 0.25
self.iou_threshold = 0.45
self.class_filter = ''
# 连接按钮事件
self.imageButton.clicked.connect(self.load_image)
self.videoButton.clicked.connect(self.load_video)
self.trackButton.clicked.connect(self.start_tracking)
self.countButton.clicked.connect(self.vehicle_count)
self.datasetButton.clicked.connect(self.generate_dataset)
self.graphButton.clicked.connect(self.analyze_data)
self.exportButton.clicked.connect(self.export_data)
# 设置滑块和输入框
self.confSlider.valueChanged.connect(self.update_confidence)
self.iouSlider.valueChanged.connect(self.update_iou)
self.classInput.textChanged.connect(self.update_class_filter)
# 其他初始化设置
self.cap = None
self.tracker = cv2.TrackerCSRT_create()
self.vehicle_count = 0
self.data = []
def load_image(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "选择图片", "", "Images (*.png *.xpm *.jpg *.bmp);;All Files (*)", options=options)
if file_name:
self.detect_vehicle(file_name)
def load_video(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "选择视频", "", "Videos (*.mp4 *.avi);;All Files (*)", options=options)
if file_name:
self.cap = cv2.VideoCapture(file_name)
self.videoPathLabel.setText(file_name)
self.startButton.setEnabled(True)
def start_tracking(self):
if self.cap is not None:
ret, frame = self.cap.read()
if ret:
results = self.model(frame, conf=self.confidence_threshold, iou=self.iou_threshold)
for result in results:
boxes = result.boxes.xyxy.cpu().numpy()
labels = result.names
for box in boxes:
x1, y1, x2, y2 = map(int, box[:4])
cls_id = int(box[5])
label = labels[cls_id]
if label == 'car':
self.tracker.init(frame, (x1, y1, x2–x1, y2–y1))
break
self.timer = QTimer()
self.timer.timeout.connect(self.track_vehicle)
self.timer.start(30) # 每30毫秒更新一次帧
def track_vehicle(self):
ret, frame = self.cap.read()
if not ret:
self.stop_tracking()
return
success, bbox = self.tracker.update(frame)
if success:
x, y, w, h = map(int, bbox)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
height, width, channel = frame.shape
bytes_per_line = 3 * width
q_img = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888)
self.imageLabel.setPixmap(QPixmap.fromImage(q_img))
def stop_tracking(self):
if self.cap is not None:
self.cap.release()
self.cap = None
self.timer.stop()
def vehicle_count(self):
# 实现车辆计数逻辑
pass
def generate_dataset(self):
# 实现数据集生成逻辑
pass
def analyze_data(self):
# 实现数据分析逻辑
pass
def export_data(self):
# 实现数据导出逻辑
pass
def detect_vehicle(self, source):
results = self.model(source, conf=self.confidence_threshold, iou=self.iou_threshold)
for result in results:
boxes = result.boxes.xyxy.cpu().numpy()
labels = result.names
for box in boxes:
x1, y1, x2, y2 = map(int, box[:4])
cls_id = int(box[5])
label = labels[cls_id]
if isinstance(source, str): # 图片
img = cv2.imread(source)
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f'{label}', (x1, y1 – 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
height, width, channel = img.shape
bytes_per_line = 3 * width
q_img = QImage(img.data, width, height, bytes_per_line, QImage.Format_RGB888)
self.imageLabel.setPixmap(QPixmap.fromImage(q_img))
elif isinstance(source, np.ndarray): # 视频帧
cv2.rectangle(source, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(source, f'{label}', (x1, y1 – 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
def update_confidence(self, value):
self.confidence_threshold = value / 100.0
def update_iou(self, value):
self.iou_threshold = value / 100.0
def update_class_filter(self, text):
self.class_filter = text
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = VehicleTrajectoryApp()
ex.show()
sys.exit(app.exec_())
4. 数据库操作示例
在需要进行数据库操作的地方,可以使用如下代码:
def insert_data(self, data):
cursor = self.db_connection.cursor()
query = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
cursor.execute(query, data)
self.db_connection.commit()
cursor.close()
请根据实际需求调整表名和列名。
以上代码提供了一个基本框架,你可以根据具体需求进一步完善和优化各个功能模块。
1. UI界面设计
首先,需要创建一个UI文件来定义你的应用程序界面。你可以使用Qt Designer工具来生成.ui文件。假设我们创建了一个名为vehicle_trajectory.ui的文件,它包含选择图片、视频文件进行分析以及显示结果的功能。
vehicle_trajectory.ui 示例内容:
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>车辆轨迹识别与检测系统</string>
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPushButton" name="loadImageButton">
<property name="text">
<string>加载图片</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="loadVideoButton">
<property name="text">
<string>加载视频</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="imageLabel">
<property name="text">
<string>图像/视频区域</string>
</property>
</widget>
</item>
<item>
<widget class="QTextEdit" name="resultText">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
使用pyuic5将.ui文件转换为Python代码:
pyuic5 vehicle_trajectory.ui -o vehicle_trajectory_ui.py
2. 主程序开发
接下来,我们将创建主程序文件(如main.py),用于加载模型、处理用户输入并展示结果。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5.QtGui import QPixmap, QImage
from vehicle_trajectory_ui import Ui_MainWindow
from ultralytics import YOLO
import cv2
class VehicleTrajectoryApp(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.model = YOLO('runs/detect/exp/weights/best.pt') # 替换为你的模型路径
self.loadImageButton.clicked.connect(self.load_image)
self.loadVideoButton.clicked.connect(self.load_video)
def load_image(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "选择图片", "", "Images (*.png *.xpm *.jpg *.bmp);;All Files (*)", options=options)
if file_name:
self.detect_vehicle(file_name)
def load_video(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "选择视频", "", "Videos (*.mp4 *.avi);;All Files (*)", options=options)
if file_name:
cap = cv2.VideoCapture(file_name)
while True:
ret, frame = cap.read()
if not ret:
break
self.detect_vehicle(frame)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
def detect_vehicle(self, source):
results = self.model(source)
for result in results:
boxes = result.boxes.xyxy.cpu().numpy()
labels = result.names
for box in boxes:
x1, y1, x2, y2 = map(int, box[:4])
cls_id = int(box[5])
label = labels[cls_id]
if isinstance(source, str): # 图片
img = cv2.imread(source)
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f'{label}', (x1, y1 – 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
height, width, channel = img.shape
bytes_per_line = 3 * width
q_img = QImage(img.data, width, height, bytes_per_line, QImage.Format_RGB888)
self.imageLabel.setPixmap(QPixmap.fromImage(q_img))
elif isinstance(source, np.ndarray): # 视频帧
cv2.rectangle(source, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(source, f'{label}', (x1, y1 – 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = VehicleTrajectoryApp()
ex.show()
sys.exit(app.exec_())
3. 数据库配置(可选)
如果你需要登录页面和数据库支持,可以使用MySQL或其他数据库管理系统。以下是简单的示例,说明如何在PyQt中连接MySQL数据库:
首先,安装必要的依赖:
pip install mysql-connector-python
然后,在你的代码中添加数据库连接逻辑:
import mysql.connector
def connect_to_database():
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
return connection
文字及代码仅供参考学习。




