A Guide to Detecting PPE Kit Violations in Factories Using YOLOv8

Home / Vision AI Guides

Vision AI Guides

A Guide to Detecting PPE Kit Violations in Factories Using YOLOv8

Team Awareye
September 30, 2024
5 min read

Workplace safety has become a top priority in many industries, especially in environments where wearing safety gear is crucial to preventing accidents and injuries. With advancements in AI and computer vision, automated safety gear detection has become a reality, helping companies ensure worker safety and compliance. A key development in this area is the use of object detection models like YOLOv8, which can accurately identify whether workers are wearing the required personal protective equipment (PPE), such as helmets, masks, and vests, in real-time.

In this project, we will guide you through the process of building a safety gear detection system using YOLOv8, one of the latest and most powerful object detection models. From preparing the dataset to training the model and deploying it for safety monitoring, you will learn how to create a robust solution that enhances safety compliance and contributes to a safer working environment. Additionally, we will explain how YOLOv8, when coupled with the DeepStream SDK, can automate alerts for PPE violations.

Understanding YOLOv8

YOLO stands for “You Only Look Once”. It is a state-of-the-art, real-time object detection system, highly popular for its speed and accuracy in detecting objects within images. YOLO operates by applying a single neural network to the entire image, which then divides the image into regions and predicts bounding boxes and probabilities for each region. These bounding boxes are assigned weights based on the predicted probabilities, enabling YOLO to perform object detection rapidly and effectively.

Key Features of YOLOv8

  • Enhanced Architecture: YOLOv8 features an improved architecture that balances computational efficiency with detection accuracy. It incorporates new techniques and layers for better feature extraction and processing.
  • Improved Detection Capabilities: The model can detect objects of various sizes and shapes in different contexts, allowing it to handle a wide range of object scales and aspect ratios.
  • Flexibility: YOLOv8 is adaptable to various tasks, such as object detection, image segmentation, and classification, making it a versatile tool for a wide range of computer vision challenges.
  • High Efficiency: YOLOv8 achieves faster inference times without sacrificing accuracy, making it ideal for real-time applications such as video surveillance, autonomous vehicles, and robotics.
  • Support for Modern Hardware: YOLOv8 is optimized to run on modern hardware, including GPUs and edge devices, enabling deployment in diverse environments, from high-performance servers to resource-constrained devices.
  • User-Friendly: The latest version is easier to use, with improved integration into popular deep learning frameworks and a more intuitive setup process. This ensures that both beginners and experienced developers can easily implement and customize the model for their specific needs.

Building a Safety Gear Detection System Using YOLOv8: Step-by-Step Guide

Prerequisites

You will need access to a GPU-powered server. We will assume that you have that ready. Alternatively, you can reach out to us for a demo of a pre-installed and containerized setup that contains DeepStream SDK and YOLO model series pre-installed. 

Let’s first create a Python virtual environment. Then, make sure you have the following libraries installed:

! pip install opencv-python
! pip install ultralytics
! pip install labelimg

Step 1: Download the Dataset and Define Input Directories 

We will use a dataset from Kaggle which contains images that are similar to real-life scenarios. In actual factory settings, you would be using video feeds from cameras installed in appropriate locations. 

Let’s download the dataset from kaggle and import the libraries.

import numpy as np
import yaml
from PIL import Image
import os
from ultralytics import YOLO
import glob

Step 2: Declare the Location of Directories and Classes

Now, declare the location of the image dataset and your working directory, and mention the number of classes you want to detect.

The classes here are important; they help you define exactly what you want to identify in the image.

INPUT_DIR = '/content/drive/MyDrive/safety-gear-detection/dataset'
WORK_DIR = '/content/drive/MyDrive/safety-gear-detection/working'


num_classes = 10
classes = ['Hardhat', 'Mask', 'NO-Hardhat', 'NO-Mask', 'NO-Safety Vest', 'Person', 'Safety Cone', 'Safety Vest', 'machinery', 'vehicle']

Step 3: Create the Configuration File

We will now create a YAML file that specifies the dataset paths and classes. This YAML file will be required by YOLO for training the model:

dict_file = {'train': os.path.join(INPUT_DIR, 'train'),
            'val': os.path.join(INPUT_DIR, 'valid'),
            'test': os.path.join(INPUT_DIR, 'test'),
            'nc': num_classes,
            'names': classes
           }


with open(os.path.join(WORK_DIR, 'data.yaml'), 'w+') as file:
   yaml.dump(dict_file, file)

Step 4: Check the Image Sizes

It is good practice to check if all images have the same size before training.

for mode in ['train', 'valid', 'test']:
   print(f'\nImage sizes in {mode} set:\n')
   img_size = 0
   for file in glob.glob(os.path.join(INPUT_DIR, mode, 'images', '*')):
       image = Image.open(file)
       if image.size != img_size:
           print(f'\t{image.size}')
           img_size = image.size

Step 5: Check the Dataset Size

Print the number of images in each dataset to verify the dataset size.

for mode in ['train', 'valid', 'test']:
   files =  glob.glob(os.path.join(INPUT_DIR, mode, 'images', '*'))
   print(f'{mode} set size: {len(files)}\n')

Step 6: Train the Custom YOLO Model

You can now train the YOLO model for safety gear detection using the given dataset. You can customize parameters like image size, number of epochs, and batch size based on your dataset and requirements.

model = YOLO('yolov8n.pt')


model.train(data=os.path.join(WORK_DIR,'data.yaml'),
           task='detect',
           imgsz=640,
           epochs=30,
           batch=32,
           mode='train',
           name='yolov8n_v1_train')

Training the YOLO model ensures that it has high accuracy when detecting the classes you specified. We recommend training the model on advanced GPUs like A100, L4 or H100. 

Step 7: Import and Test the Trained Model

After the model has been trained, you can import it and test it on images and real-time videos as well.

model = YOLO('runs/detect/yolov8n_v1_train/weights/best.pt')


results = model.predict(source=os.path.join(INPUT_DIR, 'test', 'images'), save=True)

Step 8: Visualize the Predictions

You can now visualize the model's predictions using the Matplotlib and glob libraries.

%matplotlib inline


predicitions = glob.glob(os.path.join('runs/detect/predict', '*'))


n = 10
for i in range(n):
   idx = np.random.randint(0, len(predicitions))
   image = Image.open(predicitions[idx])
   plt.imshow(image)
   plt.grid(False)
   plt.show()

Output

How Awareye Uses YOLO and DeepStream SDK to Automate PPE Violation Detection

Awareye leverages the powerful combination of YOLOv8 and NVIDIA’s DeepStream SDK to automate the detection of personal protective equipment (PPE) violations in real-time. 

Here’s how it works:

  1. Real-Time Detection with YOLOv8: Awareye’s system uses trained YOLOv8 to process live video feeds from existing surveillance cameras, accurately identifying workers who are not wearing required safety gear such as helmets, masks, or safety vests. YOLOv8’s single-stage architecture ensures the detection happens in real-time, allowing immediate action to be taken if violations occur.
  2. DeepStream SDK for Multi-Camera Support: By integrating with NVIDIA’s DeepStream SDK, Awareye can handle multiple camera feeds simultaneously. This ensures comprehensive coverage of large factory floors or work sites by eliminating blind spots, and ensuring that every corner of the facility is monitored for safety compliance. We can use YOLO-powered detection over thousands of cameras. 
  3. Automated Alerts: Once a violation is detected, the system can be configured to automatically trigger alerts or notifications to the relevant personnel, enabling quick response. We can easily integrate the alerts with PCB boards and other analog systems, and even create WhatsApp notifications. 
  4. Scalability and Efficiency: Awareye’s solution is optimized to run on on-prem GPU-powered servers, making it scalable and suitable for a wide range of industries. The system is designed to work with existing camera infrastructure, minimizing hardware costs while maximizing safety compliance.

By combining state-of-the-art object detection with efficient video processing, Awareye ensures that your workplace remains compliant with safety regulations, helping to prevent accidents and protect your workforce.

Conclusion

Ensuring workplace safety through real-time detection of PPE violations has become easier and more efficient with advancements in AI and computer vision technologies. By using YOLOv8 alongside NVIDIA’s DeepStream SDK, enterprises can now automate the process of monitoring safety compliance, significantly reducing the risk of accidents and enhancing worker protection.

In this guide, we have walked you through the steps to set up a custom PPE detection system, from dataset preparation to training and testing the model. YOLOv8’s powerful detection capabilities, combined with DeepStream SDK's scalability, enable robust, multi-camera monitoring, real-time alerts, and seamless integration into existing systems.

By deploying such an AI-driven solution, companies not only enhance safety measures but also optimize operational efficiency, reducing manual intervention while ensuring full compliance with safety regulations.

Reach out to us to learn how we are helping companies reduce PPE violations in real time using Vision AI. 

Share this post
Use Cases
Vision AI Guides
Case Studies
AirChroma Template Image

News, Updates and Blogs

Stay updated with the latest developments in Vision AI, real-world applications, and industry innovations.

Case Studies
Case Study: Automated Vehicle Entry and Exit Monitoring
Implementing Awareye’s license plate recognition system at Best Western Resort and Country Club significantly improved the efficiency and reliability of vehicle entry and exit monitoring.
Case Studies
Case Study: Detecting Missing Labels and Missing Contents on Packaging Belt
CentralPharma significantly reduced packaging errors and improved efficiency by partnering with Awareye to integrate AI-powered camera systems for real-time label and content verification.
Case Studies
Case Study: Reducing Crowding in Common Areas at a Hospital
Aarvy Hospitals partnered with Awareye to implement an AI-powered computer vision system, significantly improving crowd control, social distancing, and safety during the COVID-19 pandemic.

Ready to Deploy Awareye AI?

Unlock smarter operations with Awareye’s AI-driven multi-camera technology. Transform your business today—contact us to learn how.

By sharing your email you're confirming that you agree with our privacy policy. Our team will reach out in 24-48 hours.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.