I am trying to make a desktop application with PyQt5 which utilizes the webcam. I saw a YouTube video in which the guy used threading to achieve that. I modified the code for my use case. The modified code is below: -
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import cv2
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Ayyo")
self.GL = QGridLayout()
self.feedLabel = QLabel()
self.GL.addWidget(self.feedLabel, 0, 0, 1, 2)
self.lineEdit = QLineEdit()
self.GL.addWidget(self.lineEdit, 1, 0, 1, 1)
self.button1 = QPushButton("Confirm")
self.button1.clicked.connect(self.confirm)
self.GL.addWidget(self.button1, 1, 1, 1, 1)
self.textEdit = QTextEdit()
self.GL.addWidget(self.textEdit, 2, 0, 2, 1)
self.button2 = QPushButton("Clear")
self.button2.clicked.connect(self.clear)
self.GL.addWidget(self.button2, 2, 1, 1, 1)
self.button3 = QPushButton("Copy")
self.GL.addWidget(self.button3, 3, 1, 1, 1)
self.webcam = Webcam()
self.webcam.start()
self.webcam.ImageUpdate.connect(self.ImageUpdateSlot)
self.setLayout(self.GL)
self.show()
def ImageUpdateSlot(self, image):
self.feedLabel.setPixmap(QPixmap.fromImage(image))
def confirm(self):
current = self.textEdit.toPlainText()
self.textEdit.setPlainText(current + self.lineEdit.text())
def clear(self):
self.textEdit.setPlainText("")
class Webcam(QThread):
ImageUpdate = pyqtSignal(QImage)
def run(self):
self.ThreadActive = True
vid = cv2.VideoCapture(0)
while True:
ret, frame = vid.read()
frame1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = QImage(frame1, frame1.shape[1], frame1.shape[0], frame1.strides[0], QImage.Format_RGB888)
self.ImageUpdate.emit(image)
app = QApplication(sys.argv)
mw = MainWindow()
# mw.show()
sys.exit(app.exec_())
When I run this, the actual program runs fine but it automatically closes after a few seconds with
Process finished with exit code -1073741819 (0xC0000005)
Blockquote
The strange thing is while debugging the code in PyCharm, it didn't close. But whenever I run the code, it automatically closes after a few seconds. Any help would be appreciated.
These are always difficult to troubleshoot, but I have found that you should avoid using QThreads while initializing the application as it sometimes causes random shutdowns.
Try:
If you want to have this feature threaded so it doesn't lock the UI, take a look at QThreadPool for PyQt5 (https://www.mfitzp.com/tutorials/multithreading-pyqt-applications-qthreadpool/)
User contributions licensed under CC BY-SA 3.0