本文使用pyqt5实现对yolo系列算法进行的目标检测可视化程序的编写,其中包括登陆界面、注册界面、图片检测界面、视频检测界面、实时检测(摄像头)界面。
本文大纲
1.成品图
因为本项目对应的是yolo系统算法,故在检测功能中留有接口
2.登陆界面
以下只展示主逻辑代码
import sys
import time
from datetime import datetime
import cv2
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from ui_main import Ui_MainWindow
from ui_reg import Ui_Form
from ui_detect import Ui_Form_2
# 静态载入
class mainwindow(Ui_MainWindow, QMainWindow):
def login(self):
fopen = open('user.txt', 'r')
lines = fopen.readlines()
users=[]
pwds=[]
i = 0
for line in lines:
i+=1
line = line.strip('\n') # 去掉换行符
if i%2==0:
pwds.append(str(line))
else:
users.append(str(line))
if self.lineEdit.text() == users[0] and self.lineEdit_2.text() == pwds[0]:
self.label_4.setText("登陆成功!3秒后进入系统")
QApplication.processEvents()
time.sleep(3)
self.close()
self.detect_show(users[0])
else:
self.label_4.setText("登陆失败,请注册!")
QApplication.processEvents()
3.注册界面
def reg(self):
if self.ui2.lineEdit.text() == '' or self.ui2.lineEdit_2.text() == '' or self.ui2.lineEdit_3.text() == '':
self.ui2.label_4.setText("用户密码不能为空!")
elif self.ui2.lineEdit_2.text() != self.ui2.lineEdit_3.text():
self.ui2.label_4.setText("两次输入的密码不同,请重新输入!")
else:
newuser = self.ui2.lineEdit.text()
newpwd = self.ui2.lineEdit_2.text()
self.ui2.label_4.setText("注册成功!")
file_handle = open('user.txt', mode='w')
file_handle.write(newuser+'\n')
file_handle.write(newpwd + '\n')
file_handle.close()
QApplication.processEvents()
4.图片检测界面
def open_image(self):
imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
imgName_cv2 = cv2.imread(imgName)
try:
if imgName_cv2.all != None:
im0 = cv2.cvtColor(imgName_cv2, cv2.COLOR_RGB2BGR)
# 这里使用cv2把这张图片读取进来,也可以用QtGui.QPixmap方式。然后由于cv2读取的跟等下显示的RGB顺序不一样,所以需要转换一下顺序
showImage = QtGui.QImage(im0, im0.shape[1], im0.shape[0], 3 * im0.shape[1], QtGui.QImage.Format_RGB888)
self.ui3.label.setPixmap(QtGui.QPixmap.fromImage(showImage))
# 然后这个时候就可以显示一张图片了。
except Exception as e:
print(str(e))
self.ui3.label_3.setText("不能含有中午路径")
QApplication.processEvents()
5.视频检测界面
def cvImgtoQtImg(self,cvImg): # 定义opencv图像转PyQt图像的函数
QtImgBuf = cv2.cvtColor(cvImg, cv2.COLOR_BGR2BGRA)
QtImg = QtGui.QImage(QtImgBuf.data, QtImgBuf.shape[1], QtImgBuf.shape[0], QtGui.QImage.Format_RGB32)
return QtImg
def open_video(self):
videoName, videoType = QFileDialog.getOpenFileName(self, "打开视频", "", "*.mp4;;All Files(*)")
try:
cap = cv2.VideoCapture(videoName) # 打开影片
fps = 24
if not cap.isOpened():
print("Cannot open Video File")
while True:
ret, frame = cap.read() # 逐帧读取影片
if not ret:
if frame is None:
print("The video has end.")
else:
print("Read video error!")
break
QtImg = self.cvImgtoQtImg(frame) # 将帧数据转换为PyQt图像格式
self.ui3.label_11.setPixmap(QtGui.QPixmap.fromImage(QtImg)) # 在ImgDisp显示图像
size = QtImg.size()
self.ui3.label_11.resize(size) # 根据帧大小调整标签大小
self.ui3.label_11.show() # 刷新界面
cv2.waitKey(int(1000 / fps)) # 休眠一会,确保每秒播放fps帧
except Exception as e:
print(str(e))
self.ui3.label_3.setText("不能含有中午路径")
QApplication.processEvents()
# 完成所有操作后,释放捕获器
cap.release()
6.实时监测界面
def open_cam(self):
self.camcapture = cv2.VideoCapture(0)
self.timer = QtCore.QTimer()
self.timer.start()
self.timer.setInterval(3) # 0.1s刷新一次
self.timer.timeout.connect(self.camshow)
def camshow(self):
# global self.camimg
_, self.camimg = self.camcapture.read()
camimg = cv2.cvtColor(self.camimg, cv2.COLOR_BGR2RGB)
showImage = QtGui.QImage(camimg.data, camimg.shape[1], camimg.shape[0], QtGui.QImage.Format_RGB888)
self.ui3.label_9.setPixmap(QtGui.QPixmap.fromImage(showImage))
源码下载:传送门
本人在编写过程中遇到许多问题,这里记录一下:
- 有父窗口和子窗口,进入子窗口后点击按钮单独关闭子窗口而父窗口不关闭
解决办法:在pyqt中添加一个信号(使用self.close错误)
- 在父窗口上添加子窗口
解决办法:创建一个新的Form窗口,引用新建的ui_reg.py文件(这里ui_reg.py为子窗口文件)
from ui_reg import Ui_Form
class.....
def reg_show(self):
form = QDialog()
self.ui2 = Ui_Form()
self.ui2.setupUi(form)
# form.setWindowModality(Qt.NonModal) # 非模态,可与其他窗口交互
# form.setWindowModality(Qt.WindowModal) # 窗口模态,当前未处理完,阻止与父窗口交互
form.setWindowModality(Qt.ApplicationModal) # 应用程序模态,阻止与任何其他窗口交互
form.show()
self.ui2.label_6.setText(str(datetime.now().strftime("%Y-%m-%d")))
QApplication.processEvents()
form.exec_()
- 刷新页面问题
解决办法:添加语句 QApplication.processEvents()