How to Build PPE Detection with YOLOv11

How To Build PPE Detection Using YOLO

In this tutorial, we will walk through the process of building a Personal Protective Equipment (PPE) detection system using YOLO (You Only Look Once), one of the most popular and efficient deep learning models for object detection. This system will detect safety items such as hardhats, vests, and safety glasses, ensuring the protection of workers in various environments, especially construction sites.

Prerequisites

Before we dive into the installation and coding, make sure you have the following:

  1. Basic Python knowledge – Understanding of Python programming.
  2. Python installed – Make sure Python is installed on your machine. You can download it from here.
  3. A webcam – This tutorial uses webcam input to detect PPE items in real time.
  4. Familiarity with OpenCV – OpenCV is used to capture the webcam feed and display results.

Installation

Before running the code, you need to install the required dependencies. You can do this using pip. Open your terminal and run the following commands:

  1. Install the required libraries:
    • pip install opencv-python ultralytics numpy

Download YOLO Model

To download the YOLO model for PPE detection, follow these steps:

  1. Download the model: Visit the following link to download the pre-trained YOLO model (bestn.pt file): Download YOLOv11 Model.
  2. Save the model to your project directory.

Once you have everything set up, you’re ready to start coding.

Complete Code for PPE Detection

import cv2
import numpy as np
from ultralytics import YOLO

class PPEApp:
    def __init__(self):
        # Initialize the YOLO model
        self.model = YOLO("bestn.pt")  # Replace with your model path
        self.confidence_threshold = 0.8

        # Initialize webcam
        self.cap = cv2.VideoCapture(0)
        if not self.cap.isOpened():
            print("Error: Unable to access the webcam.")
            exit()

        # Set the video window size to fullscreen
        cv2.namedWindow("PPE Detection", cv2.WINDOW_NORMAL)
        cv2.setWindowProperty("PPE Detection", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

    def update_frame(self):
        ret, frame = self.cap.read()
        if not ret:
            print("Failed to capture frame.")
            return

        # Perform YOLO inference with dynamic confidence
        results = self.model(frame, conf=self.confidence_threshold, iou=0.3)

        # Initialize counters
        hardhat_count = 0
        vest_count = 0
        glasses_count = 0

        # Count detected items
        if len(results[0].boxes) > 0:
            detections = results[0].boxes.cls
            for det in detections:
                label = results[0].names[int(det)]
                if label == 'hardhat':
                    hardhat_count += 1
                elif label == 'vest':
                    vest_count += 1
                elif label == 'safety glasses':
                    glasses_count += 1

        # Annotate frame
        annotated_frame = results[0].plot()

        # Status messages
        hardhat_status = 'Yes' if hardhat_count > 0 else 'No'
        vest_status = 'Yes' if vest_count > 0 else 'No'
        glasses_status = 'Yes' if glasses_count > 0 else 'No'

        # Display status with appropriate colors (only Yes/No in color)
        font_scale = 0.7  # Smaller font size
        thickness = 2     # Slightly thinner text

        # Hardhat
        cv2.putText(annotated_frame, "Hardhat: ", 
                    (50, 50), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), thickness)
        cv2.putText(annotated_frame, hardhat_status, 
                    (150, 50), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 255, 0) if hardhat_status == 'Yes' else (0, 0, 255), thickness)

        # Vest
        cv2.putText(annotated_frame, "Vest: ", 
                    (50, 90), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), thickness)
        cv2.putText(annotated_frame, vest_status, 
                    (150, 90), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 255, 0) if vest_status == 'Yes' else (0, 0, 255), thickness)

        # Safety Glasses
        cv2.putText(annotated_frame, "Safety Glasses: ", 
                    (50, 130), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), thickness)
        cv2.putText(annotated_frame, glasses_status, 
                    (200, 130), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 255, 0) if glasses_status == 'Yes' else (0, 0, 255), thickness)

        # Display the annotated frame
        cv2.imshow("PPE Detection", annotated_frame)

    def run(self):
        while True:
            self.update_frame()

            # Press 'q' to quit
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        # Release the webcam and close any open windows
        self.cap.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    app = PPEApp()
    app.run()
</code>

Code Explanation

  1. YOLO Model Initialization: The YOLO model is loaded with self.model = YOLO("bestn.pt"). Make sure to provide the correct path to your model.
  2. Webcam Setup: We initialize the webcam using OpenCV’s cv2.VideoCapture(0). This will capture video from the default webcam.
  3. Detection Logic: The model performs inference on each frame captured from the webcam. The detected PPE items (e.g., hardhat, vest, glasses) are counted and displayed.
  4. Frame Annotation: We annotate the frame with “Yes” or “No” messages, indicating whether each PPE item was detected. This is done using OpenCV’s cv2.putText().
  5. Display the Frame: The annotated frame is shown in a fullscreen window.

Wrap-Up

In this tutorial, we’ve walked through building a real-time PPE detection system using YOLO. This system can be deployed on construction sites or other environments to ensure safety compliance by detecting hardhats, vests, and safety glasses. We also covered the installation steps, code, and how to run the application.

By following this tutorial, you now have a robust foundation for implementing PPE detection with YOLO. You can extend this project to detect other types of PPE or further optimize the detection system for various environments. Happy coding!

For a more detailed explanation, including visual walk through, be sure to check out our YouTube tutorial and blog for additional insights and examples. These resources will guide you step-by-step through the process and help you understand the concepts in depth!

Leave a Comment

Your email address will not be published. Required fields are marked *


Shopping Basket
Scroll to Top