Unsolved How to record the video from a webcam in a pyqt5 gui using OpenCV and QThread?
-
I'm trying to make pyqt5 Gui that shows a webcam live feed, records the feed at the same time, and saves it locally when closed. I managed to acheieve this using Timer(QTimer) in pyqt gui but When I try to implement it using Qthread (Which I really require) only the live feed is working.
Whenever I add Code required for recording video and run the program it says Python has Stopped Working and closes. Here is my Code:
import cv2 import sys from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QVBoxLayout from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot from PyQt5.QtGui import QImage, QPixmap class Thread(QThread): changePixmap = pyqtSignal(QImage) def run(self): self.cap = cv2.VideoCapture(0) self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) self.codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') self.writer = cv2.VideoWriter('output.avi', self.codec, 30.0, (self.width, self.height)) while self.cap.isOpened(): ret, self.frame = self.cap.read() if ret: self.frame = cv2.flip(self.frame, 1) rgbimage = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB) h, w, ch = rgbimage.shape bytesPerLine = ch * w convertToQtFormat = QImage(rgbimage.data, w, h, bytesPerLine, QImage.Format_RGB888) p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio) self.changePixmap.emit(p) class MyApp(QWidget): def __init__(self): super(MyApp, self).__init__() self.title = 'Camera' self.initUI() def initUI(self): self.label = QLabel(self) lay = QVBoxLayout() lay.addWidget(self.label) self.setLayout(lay) self.th = Thread() self.th.changePixmap.connect(self.setImage) self.th.start() self.show() @pyqtSlot(QImage) def setImage(self, image): self.label.setPixmap(QPixmap.fromImage(image)) self.th.writer.write(image) def main(): app = QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_()) if __name__ == '__main__': main()
I tried placing the .write() inside the run() of Thread class as well which is showing the same error. Can you guys point out What I'm doing wrong and how to make it work. I'm new to python and pyqt. Thanks in Advance.
-
@Denni-0 First of all, Thanks for the new info. I didn't know that QThreads had such an issue. I'll try the same with Multiprocessing now. By the way Would it make any difference if I used QThreadpool and sub-classed QRunnable and did the same.
I directly went to QThread because it was suggested more. Also my code has only one long running process of playback and recording (I wish to do that together since the read frame is used for both the purpose ), the main thread has only some setting up of the gui. -
@Denni-0 Understood. Much appreciate the help. I'm now looking into Multi Processing. Will update after I tried it on the above issue.
-
@Denni-0 can you help me? I am trying to achieve similar kind of thing but with detections