| title | PPE Detection |
|---|---|
| emoji | 🦺 |
| colorFrom | blue |
| colorTo | green |
| sdk | docker |
| app_port | 8501 |
| pinned | false |
| license | mit |
This project implements a comprehensive Personal Protective Equipment (PPE) detection system using both deep learning (YOLO) and traditional machine learning approaches.
Get up and running in 3 simple steps - no training required! The repository includes pre-trained models.
# 1. Clone the repository (includes pre-trained models)
git clone https://github.com/tob-git/PPL-detection.git
cd PPL-detection
# 2. Install dependencies
pip install -r requirements.txt
# 3. Launch the web UI
streamlit run app.pyThen open your browser to http://localhost:8501 and start detecting PPE immediately!
Note: The repository includes pre-trained models in the models/ directory, so you can skip the training step and start using the application right away.
The project meets all required machine learning pipeline components:
- Dataset: Construction PPE dataset with 11 classes
- Training set: 1,132 images
- Validation set: 143 images
- Test set: 141 images
- Classes: helmet, gloves, vest, boots, goggles, none, Person, no_helmet, no_goggle, no_gloves, no_boots
Multiple feature types extracted from images:
- Color Features: RGB and HSV histograms (160 features)
- Texture Features: Sobel gradients, Laplacian variance, gray-level statistics
- Shape Features: Contour-based features, edge density
- Statistical Features: Mean, std, median, percentiles per channel
Three feature selection methods implemented:
- SelectKBest: ANOVA F-test based selection
- PCA: Principal Component Analysis for dimensionality reduction
- RFE: Recursive Feature Elimination with Random Forest
Six different classifiers implemented:
- Decision Tree: Simple tree-based classifier
- Random Forest: Ensemble of decision trees
- XGBoost: Gradient boosting framework
- KNN: K-Nearest Neighbors
- SVM: Support Vector Machine with RBF kernel
- ANN (MLP): Multi-layer Perceptron neural network
Comprehensive metrics computed:
- Accuracy: Overall classification accuracy
- Precision: Per-class and weighted precision
- Recall: Per-class and weighted recall
- F1-Score: Harmonic mean of precision and recall
- Confusion Matrix: Visual representation of predictions
- Comparative Analysis: Metrics across all classifier-feature combinations
PPL detection/
├── ppe.py # YOLO-based detection pipeline
├── ml_pipeline.py # Traditional ML classification pipeline ⭐
├── infer.py # YOLO inference script
├── inferonnx.py # ONNX inference script
├── requirements.txt # Python dependencies
├── construction-ppe.yaml # Dataset configuration
├── datasets/
│ └── construction-ppe/
│ ├── images/ # Image files
│ │ ├── train/
│ │ ├── val/
│ │ └── test/
│ └── labels/ # YOLO format labels
│ ├── train/
│ ├── val/
│ └── test/
├── models/
│ ├── ppe_yolov8.pt # Trained YOLO model
│ └── ppe_yolov8.onnx # ONNX format model
└── outputs/
├── ml_pipeline/ # ML pipeline results
│ ├── confusion_matrix_*.png
│ ├── metrics_comparison.png
│ ├── detailed_metrics.csv
│ ├── features_train.pkl
│ └── features_test.pkl
├── label_vis_train/ # Label visualizations
└── label_vis_val/
git clone https://github.com/tob-git/PPL-detection.git
cd PPL-detectionOr navigate to your project directory.
python -m venv venv
source venv/bin/activate # On macOS/Linux
# or
venv\Scripts\activate # On Windowspip install -r requirements.txtThe Construction-PPE dataset needs to be downloaded before training. You have two options:
The dataset will be automatically downloaded when you first run the training script:
python ppe.pyThe YOLOv8 training script will:
- Automatically download the dataset from the official source
- Extract it to
datasets/construction-ppe/ - Organize images into train/val/test splits
If you prefer to download manually:
-
Download the dataset:
wget https://github.com/ultralytics/assets/releases/download/v0.0.0/construction-ppe.zip
-
Extract to the correct location:
unzip construction-ppe.zip -d datasets/
-
Verify the structure:
datasets/construction-ppe/ ├── images/ │ ├── train/ (1,132 images) │ ├── val/ (143 images) │ └── test/ (141 images) └── labels/ ├── train/ ├── val/ └── test/
Dataset Details:
- Size: 178.4 MB
- Total Images: 1,416 images
- Classes: 11 PPE-related classes
- Source: Ultralytics Construction-PPE dataset
- License: Check LICENSE file in dataset directory
Launch the Streamlit web interface for easy image upload and real-time predictions:
streamlit run app.pyThis will:
- Open a web browser at
http://localhost:8501 - Provide a user-friendly interface for uploading images
- Allow you to choose between YOLO or Traditional ML models
- Display predictions with visual annotations
- Compare different classifiers side-by-side
UI Features:
- ✅ Drag-and-drop image upload
- ✅ Real-time YOLO object detection with bounding boxes
- ✅ Traditional ML classification with 6+ classifiers
- ✅ Confidence scores and safety assessments
- ✅ Color-coded results (green = safe, red = unsafe)
Note: You must train models first (see Option 2 or 3) before using the UI.
Run the complete ML pipeline with feature extraction, selection, and multiple classifiers:
python ml_pipeline.pyThis will:
- ✅ Load and analyze the train/val/test dataset
- ✅ Extract color, texture, shape, and statistical features
- ✅ Apply multiple feature selection methods (SelectKBest, PCA, RFE)
- ✅ Train 6 different classifiers (Decision Tree, RF, XGBoost, KNN, SVM, ANN)
- ✅ Evaluate with accuracy, precision, recall, F1-score, and confusion matrices
- ✅ Generate comprehensive visualizations and comparison plots
- ✅ Save trained models for use in the UI
Output: All results saved to outputs/ml_pipeline/
Run the YOLO-based detection pipeline:
python ppe.pyThis will:
- Download dataset (if not already present)
- Analyze dataset statistics
- Generate label visualizations
- Train YOLOv8 model
- Validate and predict on test images
- Save trained model to
models/ppe_yolov8.pt
For quick inference with trained YOLO model:
python infer.pyOr for ONNX format:
python inferonnx.pyAfter running ml_pipeline.py, you'll find:
-
Confusion Matrices:
confusion_matrix_<method>_<classifier>.png- Visual representation of true vs predicted labels
- One for each classifier-feature method combination
-
Metrics Comparison:
metrics_comparison.png- Bar plots comparing Accuracy, Precision, Recall, F1-Score
- Across all classifiers and feature selection methods
-
Detailed Metrics:
detailed_metrics.csv- Complete numerical results
- Easy to import into Excel/Google Sheets for further analysis
-
Cached Features:
features_train.pkl,features_test.pkl- Extracted features saved for quick re-runs
- Delete these to force re-extraction
SUMMARY: Best Performing Models
================================================
Best Accuracy:
Classifier: Random Forest
Feature Method: pca
Accuracy: 0.8523
Best F1-Score:
Classifier: XGBoost
Feature Method: kbest
F1-Score: 0.8467
- 160 color histogram features (BGR + HSV)
- 9 texture features (Sobel, Laplacian, gray statistics)
- 8 shape features (contours, edges)
- 15 statistical features (per-channel statistics)
- Total: ~192 features per image
- Reduces dimensionality while maintaining performance
- Compares 3 different selection strategies
- Prevents overfitting on high-dimensional data
- Tree-based: Decision Tree, Random Forest, XGBoost
- Instance-based: KNN
- Kernel-based: SVM
- Neural Network: Multi-layer Perceptron
- Find the best model for your specific use case
- Multiple metrics beyond just accuracy
- Confusion matrices for error analysis
- Visual comparisons across all combinations
- Exportable results for reports/presentations
- I. Dataset Split: ✅ Train (1132) / Val (143) / Test (141)
- II. Feature Extraction: ✅ Color, Texture, Shape, Statistical features
- III. Feature Selection: ✅ SelectKBest, PCA, RFE
- IV. Multiple Classifiers: ✅ Decision Tree, RF, XGBoost, KNN, SVM, ANN
- V. Evaluation Metrics: ✅ Accuracy, Precision, Recall, F1, Confusion Matrix
Problem: Dataset download fails or times out
Solution:
# Try manual download
wget https://github.com/ultralytics/assets/releases/download/v0.0.0/construction-ppe.zip
unzip construction-ppe.zip -d datasets/Or use curl:
curl -L https://github.com/ultralytics/assets/releases/download/v0.0.0/construction-ppe.zip -o construction-ppe.zip
unzip construction-ppe.zip -d datasets/Problem: UI shows "model not found" error
Solution: Train the models first:
# Train YOLO model
python ppe.py
# Train traditional ML models
python ml_pipeline.pyProblem: Port 8501 is already in use
Solution: Specify a different port:
streamlit run app.py --server.port 8502If you encounter memory issues:
- Reduce image size in
extract_all_features()(default: 128x128) - Process fewer images for testing
- Use feature selection methods that reduce dimensionality more
- SVM and ANN can be slow on large datasets
- Start with Random Forest or XGBoost for faster results
- Use cached features (
.pklfiles) for subsequent runs
pip install --upgrade -r requirements.txtIf streamlit run app.py fails:
pip install streamlit
# or
pip install --upgrade streamlitAfter launching the UI with streamlit run app.py:
- Click "Browse files" or drag and drop an image
- Supported formats: JPG, JPEG, PNG
- Best results with clear images showing workers and PPE
YOLO Object Detection:
- Detects and localizes multiple PPE items in the image
- Shows bounding boxes around detected objects
- Provides confidence scores for each detection
- Best for: Images with multiple workers/objects
- Detects: Helmets, gloves, vests, boots, goggles (safe and unsafe)
Traditional ML Classification:
- Classifies entire image for overall safety assessment
- Choose from 6+ different classifiers:
- Random Forest: Ensemble method, usually best accuracy
- XGBoost: Gradient boosting, fast and accurate
- SVM: Support Vector Machine, good for complex boundaries
- Decision Tree: Simple, interpretable
- KNN: Instance-based learning
- ANN (MLP): Neural network approach
- Best for: Overall safety compliance checking
YOLO Results:
- Annotated image with color-coded bounding boxes:
- 🟢 Green: Safe PPE (helmet, gloves, vest, boots, goggles)
- 🔴 Red: Missing/unsafe PPE (no_helmet, no_gloves, etc.)
- 🟡 Yellow: Person detection
- List of all detected items with confidence scores
- Safety summary (compliant/non-compliant)
ML Classification Results:
- Safety assessment: "✅ Safe PPE" or "
⚠️ Unsafe PPE" - Confidence score (0-100%)
- Predicted class label
- Feature importance (for tree-based models)
- Upload the same image multiple times
- Try different classifiers
- Compare accuracy and confidence
- Choose the best model for your use case
The project includes Docker support for easy deployment:
# Build the Docker image
docker build -t ppe-detection .
# Run the container
docker run -p 8501:8501 ppe-detectionAccess the UI at http://localhost:8501
Note: The Docker configuration is optimized for Hugging Face Spaces deployment.
Potential enhancements:
- Deep Features: Extract features from pre-trained CNNs (ResNet, VGG)
- Hyperparameter Tuning: GridSearchCV for optimal parameters
- Ensemble Methods: Combine multiple classifiers with voting
- Class Imbalance: Handle with SMOTE or class weights
- Cross-Validation: K-fold CV for more robust evaluation
This project uses the Ultralytics YOLO model which is licensed under AGPL-3.0. Dataset: Construction-PPE by Ultralytics
Author: Mohamd Tobgi
Course: Introduction to Machine Learning - Fall 2026
Project: PPE Detection with Traditional ML Pipeline