PyQt安装可以按照官网http://www.pyinstaller.org/downloads.html
python2: sudo apt-get install python-pyqt5
python3: sudo apt-get install python3-pyqt5
可以先用Designer设计.ui界面后,再利用pyqt进行调用(也可以自己用代码写,不过我比较懒,还是直接拖图标方便~~)
![](https://img.haomeiwen.com/i6449203/4acef631440ca2b2.png)
假如设计了这样一个界面,左边显示原图,右边显示灰度图,按钮START开始载入视频文件,按钮STOP停止播放(凑合看吧,就是丑了点~~~)
PyQt调用.ui文件有两种方法:
1. uic处理ui文件
在安装的PyQt5中有uic工具,在%PythonRoot%Python35/Scripts/pyuic5.exe。
在命令行中输入如下命令
pyuic5.exe -o ui_test.py test.ui
处理完成后会在同目录下生成ui_test.py。这个文件和vs + QT 开发里面的头文件ui_xxx.h是一致的,只不过是Python版的。
使用时,先调用库文件
from ui_test import Ui_test
初始化的时候,
ui = Ui_test()
即可正常使用,即使删除ui文件也不影响程序。每次修改ui都需要重新uic。是不是很烦?所以有了下面这种方法!
2. 直接调用PyQt5.uic
调用库文件
from PyQt5.uic import loadUi
初始化的时候只要一句话!!!
loadUi('test.ui', self) #定义了一个类,所以有 self
大功告成,直接使用就行!是不是很简单?
QLabel播放视频文件
使用QLabel播放视频文件的重点就在定时器QTimer!!!
当程序中需要显示时间时或者需要在程序中周期性地进行某项操作,就会用到定时器
导入QTimer模块
from PyQt5.QtCore import QTimer
初始化
self.timer_camera = QTimer()
计时并启动
self.timer_camera.start(1000) # 1000ms == 1s
self.timer_camera.timeout.connect(self.openFrame) # 连接槽函数openFrame
完整代码:
class GUI(QDialog):
""" Main GUI with two windows
One window shows the original image, and the other shows the gray image.
"""
def __init__(self, parent = None):
super(GUI, self).__init__(parent)
loadUi('test.ui', self)
self.timer_camera = QTimer() #定义定时器
video = 'xxx/xxx/xxx/xx.avi' #加载视频文件
self.cap = cv2.VideoCapture(video)
self.pushButton_start.clicked.connect(self.slotStart) # 按钮关联槽函数
self.pushButton_stop.clicked.connect(self.slotStop)
def slotStart(self):
""" Slot function to start the progamme
"""
self.timer_camera.start(100)
self.timer_camera.timeout.connect(self.openFrame)
def slotStop(self):
""" Slot function to stop the programme
"""
self.cap.release()
self.timer_camera.stop() # 停止计时器
def openFrame(self):
""" Slot function to capture frame and process it
"""
ret,frame = self.cap.read()
if(self.cap.isOpened()):
ret, frame = self.cap.read()
if ret:
gray= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray= cv2.cvtColor(gray, cv2.COLOR_BGR2RGB)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
height, width, bytesPerComponent = frame.shape
bytesPerLine = bytesPerComponent * width
q_image = QImage(frame.data, width, height, bytesPerLine,
QImage.Format_RGB888).scaled(self.label_frame.width(), self.label_frame.height())
self.label_frame.setPixmap(QPixmap.fromImage(q_image))
q_image2 = QImage(gray.data, width, height, width,
QImage.Format_RGB888).scaled(self.label_frame_process.width(), self.label_frame_process.height())
self.label_frame_process.setPixmap(QPixmap.fromImage(q_image2))
else:
self.cap.release()
self.timer_camera.stop() # 停止计时器
网友评论