Creating a Camera Application using Pyqt5


PyQt5 is one of the most popular GUI libraries available for Python, and it allows developers to create desktop applications with ease. In this document, we will walk through the process of creating a camera application using PyQt5. The camera application will allow the user to take photos, view them, and even save them.

What are the advantages of PyQt5?

PyQt5 is a Python binding for the popular cross-platform GUI toolkit, Qt. Here are some advantages of PyQt5 −

  • Cross-platform − PyQt5 is a cross-platform toolkit, which means that applications developed with it can run on multiple platforms like Windows, Mac OS X, and Linux.

  • Rich set of widgets − PyQt5 comes with a rich set of widgets, which includes buttons, labels, text boxes, tables, and many more. This makes it easy to create complex graphical user interfaces.

  • High performance − PyQt5 provides high-performance graphical rendering through OpenGL integration. This enables smooth and responsive GUIs, even when dealing with large amounts of data.

  • Easy to learn − PyQt5 is built on top of the Python programming language, which is widely known for its simplicity and ease of use. This makes it easy for developers to learn and use PyQt5 in their projects.

  • Open source − PyQt5 is an open-source project, which means that developers can access its source code and contribute to its development. This also means that PyQt5 is available for free, without any licensing fees.

  • Large community − PyQt5 has a large community of developers and users who actively contribute to its development and support. This makes it easy to find help, documentation, and examples for using PyQt5 in your projects.

Overall, PyQt5 is a powerful and flexible toolkit for developing cross-platform graphical user interfaces with Python.

Prerequisites

Before we dive into the task few things should is expected to be installed onto your system −

List of recommended settings −

  • pip install pyqt5, open-cv, numpy

  • It is expected that the user will have access to any standalone IDE such as VS-Code, PyCharm, Atom or Sublime text.

  • Even online Python compilers can also be used such as Kaggle.com, Google Cloud platform or any other will do.

  • Updated version of Python. At the time of writing the article I have used 3.10.9 version.

  • Knowledge of the use of Jupyter notebook.

  • Knowledge and application of virtual environment would be beneficial but not required.

  • It is also expected that the person will have a good understanding of statistics and mathematics.

Installing Required Libraries

The first step is to ensure that all the necessary libraries are installed. We will need PyQt5, OpenCV, and NumPy to create the camera application. The following commands can be used to install the required libraries.

Syntax

pip install PyQt5
pip install opencv-python-headless
pip install numpy

Creating the Main Window

The main window is the backbone of any application. It is where all the user interface elements will be placed. In this camera application, we will create a main window that will have a camera feed, a button to capture the photo, and a button to save the photo.

To create the main window, we will create a new PyQt5 project and import the required libraries.

import sys
import cv2
import numpy as np
from PyQt5.QtCore import Qt, QTimer, QThread, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QStatusBar, QToolBar, QAction, QFileDialog, QLabel

Next, we will create a QMainWindow and set the window title, status bar, and tool bar.

class MainWindow(QMainWindow):
   def __init__(self):
      super().__init__()

      self.setWindowTitle("Camera Application")
      self.statusBar().showMessage("Ready")
      self.toolbar = QToolBar()
      self.addToolBar(self.toolbar)
      self.label = QLabel()
      self.label.setAlignment(Qt.AlignCenter)
      self.setCentralWidget(self.label)

We will also add a QLabel to display the camera feed.

self.camera = CameraThread()
   self.camera.image.connect(self.update_image)
   self.camera.start()

   capture_action = QAction("Capture", self.toolbar)
   capture_action.setShortcut("Space")

   capture_action.triggered.connect(self.capture_photo)
   self.toolbar.addAction(capture_action)

Capturing and Saving the Photo

To capture the photo, we will create a QAction and connect it to a method that will capture the current frame from the camera feed.

def update_image(self, frame):
   frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
   image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
   self.label.setPixmap(QPixmap.fromImage(image))

   def capture_photo(self):
      frame = self.camera.frame
      frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
      image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
      filename, _ = QFileDialog.getSaveFileName(self, "Save Photo", "", "JPEG Image (*.jpg)")
      if filename:
         image.save(filename, "jpg")

The capture_photo method will capture the current frame from the camera feed, convert it to a QImage, and save it to a file using the QFileDialog.

Creating the Camera Thread

We will use a separate thread to capture the video feed from the camera. This is to prevent the GUI from freezing while capturing the video feed.

class CameraThread(QThread):
   image = pyqtSignal(np.ndarray)

   def __init__(self):
      super().__init__()
      self.capture = None

   def start_capture(self):
      self.capture = cv2.VideoCapture(0)

   def stop_capture(self):
      if self.capture:
         self.capture.release()
         self.capture = None

   def run(self):
      self.start_capture()
      while True:
         ret, frame = self.capture.read()
         if ret:
            self.image.emit(frame)

   def stop(self):
      self.stop_capture()
      super().stop()

Final Program,Code

Let us check the final and attached code below

import sys
import cv2
import numpy as np
from PyQt5.QtCore import Qt, QTimer, QThread, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QStatusBar, QToolBar, QAction, QFileDialog, QLabel

class MainWindow(QMainWindow):
   def __init__(self):
      super().__init__()

      self.setWindowTitle("Camera Application")
      self.statusBar().showMessage("Ready")
      self.toolbar = QToolBar()
      self.addToolBar(self.toolbar)
      self.label = QLabel()
      self.label.setAlignment(Qt.AlignCenter)
      self.setCentralWidget(self.label)

      self.camera = CameraThread()
      self.camera.image.connect(self.update_image)
      self.camera.start()

      capture_action = QAction("Capture", self.toolbar)
      capture_action.setShortcut("Space")

      capture_action.triggered.connect(self.capture_photo)
      self.toolbar.addAction(capture_action)

   def update_image(self, frame):
      frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
      image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
      self.label.setPixmap(QPixmap.fromImage(image))

   def capture_photo(self):
      frame = self.camera.frame
      frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
      image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
      filename, _ = QFileDialog.getSaveFileName(self, "Save Photo", "", "JPEG Image (*.jpg)")
      if filename:
         image.save(filename, "jpg")

class CameraThread(QThread):
   image = pyqtSignal(np.ndarray)

   def __init__(self):
      super().__init__()
      self.capture = None

   def start_capture(self):
      self.capture = cv2.VideoCapture(0)

   def stop_capture(self):
      if self.capture:
         self.capture.release()
         self.capture = None

   def run(self):
      self.start_capture()
      while True:
         ret, frame = self.capture.read()
         if ret:
            self.image.emit(frame)

   def stop(self):
      self.stop_capture()
      super().stop()

Output

This program only produces output in the form of an image, due to privacy rules I can’t provide my image apart from that people might face difficulty in obtaining output due to the following reason. So the readers should keep in mind the following possible errors.

  • The camera is not properly connected or is not working. Check to make sure the camera is properly connected and functioning correctly.

  • The program does not have permission to access the camera. Check your system settings to ensure that the program has permission to access the camera.

  • The program is not properly configured. Check the code to make sure that the camera settings and PyQt5 signals are properly set up.

  • There may be an issue with the version of OpenCV being used. Try updating or reinstalling OpenCV.

  • There may be an issue with the version of PyQt5 being used. Try updating or reinstalling PyQt5.

Conclusion

In this document, we have seen how to create a camera application using Pyqt5. We have covered the installation of necessary libraries, creating the main window, creating the camera thread, displaying the camera feed, and capturing/saving the photo. With this knowledge, any developer can create impressive desktop applications that involve camera feed with Pyqt5.

Updated on: 25-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements