For Some Reason, I need use pyqt to capture image instead of cv2.
My purpose is iterate cameras in my PC, then take picture automatically.
The code below is work by manually change QComboBox, but fail by for loop.
I have tried many ways, like QThread.sleep, time.sleep, QCamera.stop, even launch by QThread.
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
import os, sys, time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.cameras = QCameraInfo.availableCameras()
# this part doesn't work correctly, only last one worked
for i, cam in enumerate(self.cameras):
self.select_camera(i)
time.sleep(10)
toolbar = QToolBar("Camera Tool Bar")
self.addToolBar(toolbar)
camera_selector = QComboBox()
camera_selector.addItems([f'{i}.{cam.description()}' for i, cam in enumerate(self.cameras)])
camera_selector.currentIndexChanged.connect(self.select_camera)
toolbar.addWidget(camera_selector)
self.show()
def select_camera(self, i):
print(f"{i=:}")
self.camera = QCamera(self.cameras[i])
self.camera.setCaptureMode(QCamera.CaptureStillImage)
self.camera.start()
self.capture = QCameraImageCapture(self.camera)
timestamp = time.strftime("%d-%b-%Y-%H_%M_%S")
self.capture.capture(os.path.join(os.getcwd(), f"{i}.{timestamp}.jpg"))
if __name__ == "__main__":
App = QApplication(sys.argv)
window = MainWindow()
sys.exit(App.exec())
You ALWAYS need to remember that Qt, like all GUI systems, is event driven. Nothing gets displayed in your __init__
calls. All that does is send a few messages. Nothing will be displayed until you get into your main loop. So, you need to use a QTimer
component to get a callback every 10 seconds, and in that callback you choose your new camera and take your shot.