本篇代码在ubuntu环境下,结束线程不会使图像界面崩溃。上篇代码在ubuntu环境运行时报错,windows下运行正常。
import cv2
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout, QPushButton
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QImage, QPixmap
class MyWindow(QWidget):
def __init__(self):
super(MyWindow, self).__init__()
self.openCameraText = 'open camera'
self.closeCameraText = 'close camera'
self.initUI()
def initUI(self):
self.resize(600, 600)
self.imageLabel = QLabel()
self.cameraBtn = QPushButton(self.openCameraText)
self.cameraBtn.clicked.connect(self.cameraBtnCliked)
layout = QGridLayout()
layout.addWidget(self.imageLabel, 0, 0 , Qt.AlignCenter)
layout.addWidget(self.cameraBtn)
self.setLayout(layout)
self.show()
def cameraBtnCliked(self):
if self.cameraBtn.text() == self.openCameraText:
self.thread_capture = ThreadCapture(0)
self.thread_capture.signal_image.connect(self.showImage)
self.thread_capture.start()
self.cameraBtn.setText(self.closeCameraText)
else:
self.thread_capture.cameraFlag = False
self.thread_capture.quit()
self.cameraBtn.setText(self.openCameraText)
def showImage(self, image):
self.imageLabel.setPixmap(image)
class ThreadCapture(QThread):
signal_image = pyqtSignal(QPixmap)
def __init__(self, camerNum):
super(ThreadCapture, self).__init__()
self.camerNum = camerNum
self.cameraFlag = True
def run(self):
self.cap = cv2.VideoCapture(self.camerNum)
while self.cameraFlag:
print('Thread ID:', QThread.currentThreadId())
ret, image = self.cap.read()
image = cv2.resize(image, (500, 500))
if ret:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
qimage = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
qpixmap = QPixmap.fromImage(qimage)
self.signal_image.emit(qpixmap)
else:
self.cap.release()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWindow()
sys.exit(app.exec_())
|