YOLOv5 detection interface-PyQt5 implementation

1. Apply detect.py to the interface

To combine YOLOv5 detection results with the PyQt interface, you need to perform some additional steps. The following is a simple example code that shows how to use YOLOv5 for object detection and display the results in the PyQt interface.

First, make sure you have the necessary libraries installed:

pip install opencv-python PyQt5 torch

Then, use the following code as yolov5_detect_pyqt.py Assuming you want to use detect.py for inference, you need to replace the detect function below with f”python detect.py”:

import sys
import cv2
import torch
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QPixmap
from PyQt5.QtGui import QImage, QPixmap
from yolov5.detect import detect #Import your YOLOv5 detection function

class YOLOv5DetectApp(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('YOLOv5 Object Detection with PyQt')
        self.setGeometry(100, 100, 800, 600)

        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignCenter)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.label)

        self.setLayout(vbox)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(1000) #Set the timer interval in milliseconds

    def update_frame(self):
        #Perform target detection
        image = cv2.imread('path/to/your/image.jpg') # Replace with your image path
        results = detect(image) # Use your YOLOv5 detection function

        # Draw detection results on the image
        for result in results:
            label = result['label']
            confidence = result['confidence']
            box = result['box']

            cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
            cv2.putText(image, f"{<!-- -->label} {<!-- -->confidence:.2f}", (box[0], box[1] - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # Convert the OpenCV image to a format displayable by PyQt
        height, width, channel = image.shape
        bytes_per_line = 3 * width
        q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(q_image)

        # Display images on the PyQt interface
        self.label.setPixmap(pixmap)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = YOLOv5DetectApp()
    window.show()
    sys.exit(app.exec_())

Please note that the detect function in the above code is an example function and you need to replace it with your YOLOv5 target detection function. Make sure your object detection function returns a list containing detection results, each result is a dictionary containing label, confidence and bounding box information.

This is just a simple example, in reality, you may need to make the interface more optimized and interactive. Additionally, if your detection process is time-consuming, you may want to consider using multi-threading to ensure the responsiveness of your interface.

2. Load images or videos into the interface

If you want to trigger the loading of images or videos through a button, you can add a button in the PyQt window and trigger the loading operation through the button’s click event. Here is the modified code, which adds a button to load the image:

import sys
import cv2
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QPushButton, QFileDialog
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt, QTimer
from yolov5.detect import detect #Import your YOLOv5 detection function

class YOLOv5DetectApp(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('YOLOv5 Object Detection with PyQt')
        self.setGeometry(100, 100, 800, 600)

        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignCenter)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.label)

        #Add button to load images
        self.load_image_button = QPushButton('Load Image', self)
        self.load_image_button.clicked.connect(self.load_image)
        vbox.addWidget(self.load_image_button)

        self.setLayout(vbox)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(1000) #Set the timer interval in milliseconds

        self.image_path = None # Used to store the currently loaded image path

    def load_image(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getOpenFileName(self, "Open Image File", "", "Image Files (*.png *.jpg *.bmp);;All Files (*)", options=options)
        if file_name:
            self.image_path = file_name

    def update_frame(self):
        if self.image_path is not None:
            #Perform target detection
            image = cv2.imread(self.image_path)
            results = detect(image) # Use your YOLOv5 detection function

            # Draw detection results on the image
            for result in results:
                label = result['label']
                confidence = result['confidence']
                box = result['box']

                cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
                cv2.putText(image, f"{<!-- -->label} {<!-- -->confidence:.2f}", (box[0], box[1] - 10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

            # Convert the OpenCV image to a format displayable by PyQt
            height, width, channel = image.shape
            bytes_per_line = 3 * width
            q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(q_image)

            # Display images on the PyQt interface
            self.label.setPixmap(pixmap)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = YOLOv5DetectApp()
    window.show()
    sys.exit(app.exec_())

In this example, passing the button is achieved by adding a QPushButton instance load_image_button and connecting the clicked signal to the load_image method. Function to load images. When the button is clicked, a file dialog box will pop up, allowing the user to select an image file to load. The loaded image path is stored in self.image_path and used in the timer’s update_frame method.