我正在使用Qt设计器在Raspberry Pi 3上开发GUI,并使用PyQt在Python中编写代码。 GUI将通过串行端口与串行设备通信,并且还应从连接到Rpi3 USB的网络摄像头流式传输实时视频。
首先,我找到了一个简单的GUI,其中包含两个按钮(Begin
和Stop
),用于我所需的网络摄像头。但是流很慢。所以,我从PyImageSearch中获取了一些例子并启动了一个线程来进行网络摄像头流程。
import sys
import cv2
import numpy as np
from threading import Thread
from PyQt4 import QtGui, QtCore, Qt, uic
from PyQt4.QtCore import pyqtSlot
class WebcamStream():
def __init__(self,src=0):
self.capture = cv2.VideoCapture(src)
(self.ret, self.readFrame) = self.capture.read()
self.stopped = False
self.currentFrame=np.array([])
def start(self):
print "Stream_Start"
t = Thread(target=self.update, args=())
t.daemon = True
t.start()
return self
def update(self):
"""
capture frame and reverse RBG BGR and return opencv image
"""
while True:
if self.stopped:
return
(self.ret, self.readFrame) = self.capture.read()
self.currentFrame=cv2.cvtColor(self.readFrame,cv2.COLOR_BGR2RGB)
print "Image_Updated"
def read(self):
print "Read_File"
return self.readFrame
def stop(self):
self.stopped = True
def captureNextFrame(self):
self.read()
if(self.ret==True):
self.currentFrame=cv2.cvtColor(self.readFrame,cv2.COLOR_BGR2RGB)
print "Frame_captured"
def convertFrame(self):
""" converts frame to format suitable for QtGui """
try:
height,width=self.currentFrame.shape[:2]
img=QtGui.QImage(self.currentFrame,
width,
height,
QtGui.QImage.Format_RGB888)
img=QtGui.QPixmap.fromImage(img)
self.previousFrame = self.currentFrame
print "Frame_converted"
return img
except:
return None
class Gui(QtGui.QMainWindow):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
uic.loadUi('mainWindow.ui', self)
self.show()
self.video = WebcamStream(src=0).start()
#self._timer = QtCore.QTimer(self)
#self._timer.timeout.connect(self.play)
self.Stopp=True
self.update()
def play(self):
try:
while self.Stopp:
#self.video.captureNextFrame()
self.videoFrame.setPixmap(self.video.convertFrame())
self.videoFrame.setScaledContents(True)
cv2.waitKey(2)
except TypeError:
print "No frame"
@pyqtSlot()
def on_ButtonBegin_clicked(self):
#self._timer.start(100)
self.play()
@pyqtSlot()
def on_ButtonStop_clicked(self):
#self._timer.stop()
self.Stopp=False
self.video.stop()
cv2.destroyAllWindows()
def main():
app = QtGui.QApplication(sys.argv)
ex = Gui()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
但是这条小溪依旧呆滞。我还没有使用线程进行编程,甚至不知道我是否做得对。但我必须做线程,因为我必须进一步使用Rpi3 GPIO和串行线。