I am trying to run a while loop but when it runs my gui(PyQt5) crashes. I am trying to run a function on button press. When the btn_off_on is pressed i would like off_on method. The method runs a virtual camera and the reason i need a loop is because i constantly need to send video frames to the virtual camera, if the hotkey is pressed the frames sent to the virtual camera change from a video to live webcam.
import PyQt5.QtWidgets as qtw
import pyvirtualcam
import cv2
import keyboard
class MainWindow(qtw.QWidget):
def __init__(self):
super().__init__()
# Initiating Variables
self.path = ""
self.WIDTH = 1920
self.HEIGHT = 1080
self.FPS = 30
self.HOTKEY = "alt+shift+;"
self.cap = cv2.VideoCapture(0)
self.camera_use = False
self.FMT = pyvirtualcam.PixelFormat.BGR
# Initiating Elements
self.btn_off_on = qtw.QPushButton("On/Off")
self.btn_path = qtw.QPushButton("Get Video")
# Everything needed for PyQt5
self.setWindowTitle("Matthew's Cute")
self.setLayout(qtw.QVBoxLayout())
self.front_page()
self.show()
def off_on(self):
with pyvirtualcam.Camera(width=self.WIDTH, height=self.HEIGHT, fps=self.FPS, fmt=self.FMT) as cam:
print(pyvirtualcam.Camera)
print(f'Using virtual camera: {cam.device}')
while True:
while not self.camera_use: ##########HERE IS WHERE I RUN MY WHILE LOOP
try:
ret, frame = loop_cap.read()
frame = cv2.resize(frame, (self.WIDTH, self.HEIGHT), interpolation=cv2.INTER_AREA)
self.front_page()
self.show()
cam.send(frame)
cam.sleep_until_next_frame()
except:
loop_cap = cv2.VideoCapture(self.path[0])
self.camera_use = False
if keyboard.is_pressed(self.HOTKEY):
self.camera_use = True
while self.camera_use:
ret, frame = self.cap.read()
frame = cv2.resize(frame, (self.WIDTH, self.HEIGHT), interpolation=cv2.INTER_AREA)
super().__init__()
self.setWindowTitle("Matthew's Cute")
self.setLayout(qtw.QVBoxLayout())
self.front_page()
self.show()
cam.send(frame)
cam.sleep_until_next_frame()
if keyboard.is_pressed(self.HOTKEY):
self.camera_use = False
def get_path(self):
self.path = qtw.QFileDialog.getOpenFileName()
print(self.path[0])
def front_page(self):
container = qtw.QWidget()
container.setLayout(qtw.QGridLayout())
# Adding the buttons to the layout
container.layout().addWidget(self.btn_off_on, 0, 0, 1, 2)
self.btn_off_on.clicked.connect(self.off_on)############ HERE IS WHERE I CALL THE METHOD
container.layout().addWidget(self.btn_path, 2, 0, 1, 2)
self.btn_path.clicked.connect(self.get_path)
self.layout().addWidget(container)
if __name__ == '__main__':
app = qtw.QApplication([])
mw = MainWindow()
app.setStyle(qtw.QStyleFactory.create('Fusion'))
app.exec_()