在上一篇文章《Python学习之简易视频播放器》中,通过python-opencv-pyqt5,实现了有界面的视频播放。但是,上文代码只有播放,却无法让播放的视频暂停。这是因为,我们在播放中使用的是while(self.cap.isOpened())循环。若要让视频在播放过程可以暂停,就要借助QTimer()函数来实现了。不多说了,直接上代码:
import cv2
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QPushButton, QVBoxLayout, QLabel
class UI_FROM(QWidget):
def __init__(self):
super(UI_FROM, self).__init__()
self.resize(800, 600)
self.timer_camera = QTimer()
self.vl = QVBoxLayout(self)
self.hl = QHBoxLayout(self)
btn1 = QPushButton('播放')
btn1.clicked.connect(self.ShowCamera)
self.hl.addWidget(btn1)
btn2 = QPushButton('暂停')
btn2.clicked.connect(self.timer_camera.stop)
self.hl.addWidget(btn2)
self.vl.addLayout(self.hl)
self.label = QLabel(self)
self.label.setGeometry(20, 20, 640, 480)
self.label.setStyleSheet("QLabel{background: black;}")
self.label.setAlignment(Qt.AlignTop)
self.label.setAlignment(Qt.AlignLeft)
self.label.setFrameShape(QtWidgets.QFrame.Box)
self.label.setScaledContents(True)
self.vl.addWidget(self.label)
self.cap = cv2.VideoCapture(0)
print('摄像头是否开启: {}'.format(self.cap.isOpened()))
def Stop(self):
self.timer_camera.stop()
def ShowCamera(self):
self.timer_camera.start(100)
self.timer_camera.timeout.connect(self.ShowData)
def ShowData(self):
self.ret, color_frame = self.cap.read()
if self.ret :
color_frame = cv2.flip(color_frame, 1)
cv2.waitKey(1)
im = cv2.cvtColor(color_frame, cv2.COLOR_RGB2BGR)
img = QImage(im.data, im.shape[1], im.shape[0], QImage.Format_RGB888)
self.label.setPixmap(QPixmap.fromImage(img))
else:
self.cap.release()
self.timer_camera.stop()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ui =UI_FROM()
ui.show()
sys.exit(app.exec_())
如上代码,界面就放置了3个控件,分别是播放和暂停按钮,以及用于加载视频的QLabel,然后通过QVBoxLayout和QHBoxLayout进行了简单布局。程序执行后,会先去打开本地摄像头,然后点击播放按钮后,才会读取视频流数据。点击暂停按钮,则会通过暂停计时器,从而实现视频播放的暂停。具体效果图如下:
好了,现在可以把上面的代码和《Python学习之简易视频播放器》的代码结合一下,让播放器的功能进一步完善吧!