PyQt5 shows black window without widgets while moviepy is concatenating videos - python-3.x

When concatenating two video files, the PyQt window is completely black with no widgets. The background color changes to grey and the widget shows up only after the videos have been concatenated.
I would like to see a grey window and my widget while the videos are being concatenated.
Here is the script:
import os
import sys
from PyQt5.QtWidgets import *
from moviepy.editor import VideoFileClip, concatenate_videoclips
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Using Labels")
self.setGeometry(50,50,350,350)
self.UI()
def UI(self):
text1=QLabel("Hello Python",self)
text1.move(50,50)
self.show()
def make_movie():
sep = os.sep
directory_stub = '.' + sep + 'src' + sep + "assets" + sep
clip1 = VideoFileClip(directory_stub + 'introoutro' + sep + "intro.mp4")
clip2 = VideoFileClip(directory_stub + 'introoutro' + sep + "outro.mp4")
final_clip = concatenate_videoclips([clip1,clip2])
final_clip.write_videofile("my_concatenation.mp4")
def main():
App = QApplication(sys.argv)
window=Window()
make_movie()
sys.exit(App.exec_())
if __name__ == '__main__':
main()
While the videos are being put together I see this:
I want to see this during the video processing but I only see it 1. after the processing is done or 2. if I edit the code to never call make_movie():
Thanks for any help.

Concatenation is a very time consuming task so it should not be run on the main thread as it can freeze the GUI:
import os
import sys
import threading
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
from moviepy.editor import VideoFileClip, concatenate_videoclips
class QMovie(QObject):
started = pyqtSignal()
finished = pyqtSignal()
def concatenate(self, inputs, output):
threading.Thread(
target=self._concatenate, args=(inputs, output), daemon=True
).start()
def _concatenate(self, inputs, output):
self.started.emit()
clips = []
for input_ in inputs:
clip = VideoFileClip(input_)
clips.append(clip)
output_clip = concatenate_videoclips(clips)
output_clip.write_videofile(output)
self.finished.emit()
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Using Labels")
self.setGeometry(50, 50, 350, 350)
self.UI()
def UI(self):
text1 = QLabel("Hello Python", self)
text1.move(50, 50)
self.show()
def main():
App = QApplication(sys.argv)
window = Window()
directory_stub = os.path.join(".", "src", "assets")
in1 = os.path.join(directory_stub, "introoutro", "intro.mp4")
in2 = os.path.join(directory_stub, "introoutro", "outro.mp4")
qmovie = QMovie()
qmovie.concatenate([in1, in2], "my_concatenation.mp4")
sys.exit(App.exec_())
if __name__ == "__main__":
main()

Related

PyQt5 does not redrawing widget

Force repainting does not repaint PyQt5 widget (Qlabel, QTextEdit, even QProgressBar and etc)
Tested platforms: Linux, MacOS
PyQt5 version: 5.15.7
Installed from pip
As example I created simple app that updating text in QLabel widget in for loop. Force repainting doesnt working
import sys
from time import sleep
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel)
class Example(QWidget):
def __init__(self):
super().__init__()
self.text = QLabel('Test', self)
self.text.move(10, 10)
self.text.resize(60,20)
self.button = QPushButton('Run', self)
self.button.move(17,40)
self.button.clicked.connect(self.some_activity)
self.setGeometry(300, 300, 100, 80)
self.show()
def some_activity(self):
for i in range(100):
text = f'i = {i}'
self.text.setText(text)
# self.text.update() -> Nothing happens (it shouldnt: https://doc.qt.io/qt-5/qwidget.html#update)
self.text.repaint() # -> Nothing happens
self.repaint() # -> Nothing happens
print(f'Text updated: {text}')
sleep(0.03)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Video demonstration: link
Just needed to use QThread to use for loop in my program
Thanks #musicamante for helping.
import sys
from time import sleep
from PyQt5 import QtCore
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel)
class Thread(QtCore.QThread):
signal = QtCore.pyqtSignal(str)
def __init__(self, parent=None): QtCore.QThread.__init__(self, parent)
def run(self):
for i in range(100):
text = f'i = {i}'
print(f'Text updated: {text}')
self.signal.emit(text)
sleep(.3)
class Example(QWidget):
def __init__(self):
super().__init__()
self.text = QLabel('Test', self)
self.text.move(10, 10)
self.text.resize(60,20)
self.thread = Thread()
self.thread.signal.connect(self.signal, QtCore.Qt.QueuedConnection)
self.button = QPushButton('Run', self)
self.button.move(17,40)
self.button.clicked.connect(self.thread.start)
self.setGeometry(300, 300, 100, 80)
self.show()
def signal(self, text): self.text.setText(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

QObject: Cannot create children for a parent that is in a different thread. (Multithreading pyqt5)

I am trying to edit the text in 'QTextEdit' but I got the error which is in the title above. I know that I shouldn't edit the widgets in the main app from another thread and I searched for some answers, But I didn't get the full answer that I want
This is a sample that produce the same error that I have
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore
import sys
import time
import threading
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.move(50, 220)
self.resize(500, 500)
self.text_edit = QTextEdit(self)
self.text_edit.resize(200, 200)
self.btn = QPushButton('start', self)
self.btn.move(10, 250)
self.btn.clicked.connect(lambda x : self.thread_creator(self.test))
self.btn2 = QPushButton('print', self)
self.btn2.move(10, 290)
self.btn2.clicked.connect(lambda x : print('dad'))
def test(self):
for i in range(99):
self.text_edit.setText(f'dad {i}')
time.sleep(0.1)
def thread_creator(self, function):
self.thread = threading.Thread(target=function)
self.thread.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
ex.show()
sys.exit(app.exec_())

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.
You need to separate threads. First thread is for signal, second is for the record and the main thread is for GUI. Try the following code. There is a button to start/stop the record.
import sys
import cv2
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer, QThread, pyqtSignal, pyqtSlot
from PyQt5 import QtWidgets, QtCore, QtGui
#https://ru.stackoverflow.com/a/1150993/396441
class Thread1(QThread):
changePixmap = pyqtSignal(QImage)
def __init__(self, *args, **kwargs):
super().__init__()
def run(self):
self.cap1 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.cap1.set(3,480)
self.cap1.set(4,640)
self.cap1.set(5,30)
while True:
ret1, image1 = self.cap1.read()
if ret1:
im1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
height1, width1, channel1 = im1.shape
step1 = channel1 * width1
qImg1 = QImage(im1.data, width1, height1, step1, QImage.Format_RGB888)
self.changePixmap.emit(qImg1)
class Thread2(QThread):
def __init__(self, *args, **kwargs):
super().__init__()
self.active = True
def run(self):
if self.active:
self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.out1 = cv2.VideoWriter('output.avi', self.fourcc, 30, (640,480))
self.cap1 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.cap1.set(3, 480)
self.cap1.set(4, 640)
self.cap1.set(5, 30)
while self.active:
ret1, image1 = self.cap1.read()
if ret1:
self.out1.write(image1)
self.msleep(10)
def stop(self):
self.out1.release()
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.resize(660, 520)
self.control_bt = QPushButton('START')
self.control_bt.clicked.connect(self.controlTimer)
self.image_label = QLabel()
self.saveTimer = QTimer()
self.th1 = Thread1(self)
self.th1.changePixmap.connect(self.setImage)
self.th1.start()
vlayout = QVBoxLayout(self)
vlayout.addWidget(self.image_label)
vlayout.addWidget(self.control_bt)
#QtCore.pyqtSlot(QImage)
def setImage(self, qImg1):
self.image_label.setPixmap(QPixmap.fromImage(qImg1))
def controlTimer(self):
if not self.saveTimer.isActive():
# write video
self.saveTimer.start()
self.th2 = Thread2(self)
self.th2.active = True
self.th2.start()
# update control_bt text
self.control_bt.setText("STOP")
else:
# stop writing
self.saveTimer.stop()
self.th2.active = False
self.th2.stop()
self.th2.terminate()
# update control_bt text
self.control_bt.setText("START")
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
you placed the .write() inside the run() of Thread class is right way.
like:
...
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)
# put your writer() here, make sure your param is frame
# not converted to QtImage format
self.writer.write(rgbimage)
self.changePixmap.emit(p)
...

My gui doesn't appear when I use while loop as a startup function in pyqt and python

I want to use startup function which should have while loop.
but I run the code my gui doesn't appear until while loop ends.
I tried with self.show() it can make show gui but it doesn't allow to use sys.exit()
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic
import time
form_class,QMainWindow=uic.loadUiType('youhua.ui')
class MyWindow(QMainWindow,form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
#self.show()
self.myfunc()
def myfunc(self):
k=1
stat=True
while stat:
k=k+1
time.sleep(1)
self.statusMessage.append(str(k))
QApplication.processEvents()
if k>10:
stat=False
#sys.exit()
if __name__=='__main__':
app=QApplication(sys.argv)
myWindow=MyWindow()
myWindow.show()
app.exec_()
If you need to perform an action again, you have several options.
For example, if each iteration takes very little time, without the possibility of blocking the main loop, you can replace the cycle with a timer (QTimer) and call the method each time, which is responsible for obtaining new data and updating the necessary interface elements in accordance with them:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic
from PyQt5.QtCore import QThread, QTimer
import time
#form_class, QMainWindow = uic.loadUiType('youhua.ui')
class MyWindow(QMainWindow): #, form_class):
def __init__(self):
super().__init__()
self.k = 0
centralWidget = QtWidgets.QWidget(self)
self.setCentralWidget(centralWidget)
self.button = QtWidgets.QPushButton('Start', self)
self.button.clicked.connect(self.read_data)
self.label_data = QtWidgets.QLabel(self, alignment=QtCore.Qt.AlignCenter)
self.label_data.setText('Pending')
layout = QtWidgets.QGridLayout(centralWidget)
layout.addWidget(self.label_data)
layout.addWidget(self.button)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.read_data_from_sensor)
#QtCore.pyqtSlot()
def read_data(self):
''' Start / Stop reading at the touch of a button '''
if not self.timer.isActive():
self.timer.start()
self.button.setText("Stop")
else:
self.timer.stop()
self.button.setText("Start")
self.label_data.setText("Pending")
#QtCore.pyqtSlot()
def read_data_from_sensor(self):
dt = time.strftime("%Y-%m-%d %H:%M:%S")
self.label_data.setText(dt)
self.label_data.adjustSize()
self.k += 1
self.statusBar().showMessage('{} item(s)'.format(self.k))
if self.k > 10:
self.timer.stop()
self.button.setText("Start")
self.label_data.setText("Pending")
self.k = 0
if __name__=='__main__':
app = QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
app.exec_()
What you wrote may also work, but this is not very good. You can compare.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic
from PyQt5.QtCore import QThread
#import time
#form_class, QMainWindow = uic.loadUiType('youhua.ui')
class MyWindow(QMainWindow): #, form_class):
def __init__(self):
super().__init__()
# self.setupUi(self)
self.show()
self.myfunc()
def myfunc(self):
k = 0
stat = True
while stat:
k += 1
# time.sleep(1)
# self.statusMessage.append(str(k))
self.statusBar().showMessage('{} item(s)'.format(k))
QThread.msleep(1000)
QApplication.processEvents()
if k>10:
stat=False
#sys.exit()
if __name__=='__main__':
app = QApplication(sys.argv)
myWindow = MyWindow()
# myWindow.show()
app.exec_()
In your loop you are sleeping for 10 second, since you are creating a while loop on the main thread, the GUI wont show until the loop is done because it would be blocking the main thread. You can test this by removing time.sleep(1).
Without changing your code much, try this:
import sys,threading, time
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic
form_class,QMainWindow=uic.loadUiType('youhua.ui')
class MyWindow(QMainWindow,form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
#self.show()
t = threading.Thread(target=self.myfunc)
t.start()
def myfunc(self):
k=1
stat=True
while stat:
k=k+1
time.sleep(1)
self.statusMessage.append(str(k))
QApplication.processEvents()
if k>10:
stat=False
#sys.exit() - if you are trying to close the window here use self.close()
if __name__=='__main__':
app=QApplication(sys.argv)
myWindow=MyWindow()
myWindow.show()
sys.exit(app.exec_())

Screen functions in PYQT

import sys
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time
import datetime
import re
import random
import csv
from CropClass import *
from Wheat_class import *
from Potato_class import *
win1 = uic.loadUiType("MenuScreen.ui")[0]
win2 = uic.loadUiType("WheatScreen.ui")[0]
win3 = uic.loadUiType("PotatoScreen.ui") [0]
class MenuScreen(QtGui.QMainWindow, win1):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.BtnCreateSimulation.clicked.connect(self.changeSimulation)
def changeSimulation(self):
if self.RdoWheat.isChecked() ==True:
print("Wheat is picked")
new_crop=Wheat()
self.wheatSimulation()
elif self.RdoPotato.isChecked() == True:
print("Potato is picked")
new_crop = Potato()
self.PotatoSimulation()
def wheatSimulation(self):
print("Hello")
self.hide()
WheatWindow.show()
def PotatoSimulation(self):
self.hide()
PotatoWindow.show()
class PotatoScreen(QtGui.QMainWindow, win3):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.BtnBacktoMenu.clicked.connect(self.BackToMain)
def BackToMain(self):
self.hide()
MenuWindow.show()
class WheatScreen(QtGui.QMainWindow, win2):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
new_crop = Wheat()
self.BtnBacktoMenu.clicked.connect(self.BackToMain)
self.BtnManual.clicked.connect(self.ManualCalculate)
def BackToMain(self):
self.hide()
MenuWindow.show()
def ManualCalculate(self):
water = self.spBoxWater.value()
light= self.spBoxLight.value()
print("water", water, "light", light)
def main():
app = QtGui.QApplication(sys.argv)
WheatWindow = WheatScreen(None)
PotatoWindow = PotatoScreen(None)
MenuWindow = MenuScreen(None)
MenuWindow.show()
app.exec_()
if __name__ == "__main__":
main()
I have created a program in Python which simulates the growth rates of crops. The user is able to chose between the crop is wheat or potatoes I am trying to create a GUI using PYQT. The problem I am having is that when I try and load the program the program is not recognizing the other screen layouts. The main function should be setting up the screen layouts

Resources