An end-to-end deep learning and model interpretability system that detects, classifies, and visually localizes solar panel surface defects from drone and field inspection imagery. Built with PyTorch, fine-tuned ResNet-50, native Grad-CAM explainability, and optimized with ONNX Runtime for CPU inference.
🔗 Live Deployment: View Live App Demo
Solar photovoltaic (PV) modules are continuously exposed to environmental hazards. Dust accumulation, bird droppings, snow coverage, micro-cracks, and localized cell short circuits severely undermine farm operations:
- Energy Degradation: Soiled or covered panels dramatically decrease kilowatt-hour generation, causing recurring financial losses.
- Fire & Safety Hazards: Undetected physical cracks or internal electrical cell failures create thermal hot-spots that permanently burn modules and pose fire risks.
- The Manual Inspection Bottleneck: Manual foot patrol inspections across utility-scale farms spanning thousands of acres are slow, labor-intensive, and subjective.
This project automates inspection by classifying module conditions across 6 distinct diagnostic classes:
- Clean: Optimal, healthy panel operating at rated power.
- Dusty: Particulate buildup requiring routine scheduled cleaning.
- Bird-drop: Localized organic occlusion prone to triggering hot-spot dissipation.
- Snow-Covered: Heavy blockage requiring immediate snow removal dispatch.
- Physical-Damage: Surface cracks, shattered glass, or structural frame fractures.
- Electrical-damage: Internal cell failure, bypass diode failure, or localized short circuits.
In safety-critical industrial computer vision, black-box predictions are unacceptable. Field engineers need to verify why a model flagged a panel for physical damage versus harmless surface glare or background grass.
We implemented native Grad-CAM (Gradient-weighted Class Activation Mapping) targeting the final bottleneck block of ResNet-50 (layer4[-1]):
- Calculates gradients of the predicted class score with respect to layer 4 feature activation maps.
- Performs global average pooling of gradients to derive importance weights.
- Renders a bilinear-scaled thermal activation heatmap overlaid directly on the uploaded inspection image (
$\alpha = 0.45$ ).
| Inspection Mode | UI Output View |
|---|---|
| 📷 Field Inspection Image | Raw uploaded drone or handheld inspection photo. |
| 🔥 Grad-CAM Activation Heatmap | Thermal overlay highlighting the exact physical region that drove the model's defect classification. |
To enable cost-effective edge deployment on drone companion computers and lightweight web servers without requiring dedicated GPUs, we exported the fine-tuned PyTorch checkpoint to ONNX (opset 14) and benchmarked CPU latency.
Benchmarked across 50 timed iterations following 10 warm-up runs:
| Metric | PyTorch (CPU) | ONNX Runtime (CPU) | Speedup / Gain |
|---|---|---|---|
| Mean Latency | 47.32 ms | 19.19 ms | 59.4% Faster |
| Median (P50) | 46.61 ms | 18.86 ms | 59.5% Faster |
| 95th Percentile (P95) | 49.25 ms | 20.82 ms | 57.7% Faster |
| Latency Std Dev | 3.31 ms | 1.31 ms | More Consistent |
| Throughput | 21.1 FPS | 52.1 FPS | 2.47x Higher Throughput |
Key Takeaway: ONNX graph optimization and constant folding reduced per-frame CPU latency to ~19 ms, enabling real-time 52+ FPS inspection throughput on standard commodity hardware.
The fine-tuned model was evaluated on a stratified validation partition (20% of dataset, 177 images).
| Class | Precision | Recall | F1-Score | Support (Validation Images) |
|---|---|---|---|---|
| Bird-drop | 0.92 | 0.83 | 0.87 | 41 |
| Clean | 0.77 | 0.89 | 0.83 | 38 |
| Dusty | 0.91 | 0.79 | 0.85 | 38 |
| Electrical-damage | 0.76 | 0.90 | 0.83 | 21 |
| Physical-Damage | 0.77 | 0.71 | 0.74 | 14 |
| Snow-Covered | 0.92 | 0.92 | 0.92 | 25 |
| Overall Accuracy | - | - | 0.85 | 177 |
- Rare defects (such as Physical-Damage with only 69 total samples) naturally suffer from representation imbalance relative to Clean panels (194 samples).
- We countered this by integrating balanced class weights into Cross-Entropy Loss and employing stratified splits, heavily penalizing False Negatives.
- For operational solar maintenance, a False Negative (missing a damaged module) is catastrophic compared to a False Positive (dispatching an inspector to a clean panel). The fine-tuned pipeline achieves 90% Recall on Electrical-damage and 89% Recall on Clean modules.
flowchart TD
A[Raw Inspection Images ./data] -->|Stratified Split 80/20| B[PyTorch SolarDataset Pipeline]
B -->|Augmentation: Flips, Rotation, Jitter| C[ImageNet Normalization]
C --> D[ResNet-50 Transfer Learning: Stage 1 Warmup]
D --> E[Fine-Tuning: Stage 2 Unfreeze Layer 4 with Differential LR]
E --> F[PyTorch Checkpoint .pt]
F -->|Export & Verify| G[ONNX Optimized Model .onnx]
F -->|Explainability Hook| H[Grad-CAM Feature Activation]
G --> I[Fast CPU Serving 52 FPS]
H --> J[Streamlit Interactive UI app.py]
-
Transfer Learning Strategy: Pre-trained ImageNet ResNet-50 backbone with custom classification head (
Linear(2048, 128) -> ReLU -> Dropout(0.5) -> Linear(128, 6)). -
Two-Stage Optimization:
-
Stage 1 (Warmup): Frozen backbone, training the linear head at
$\text{LR} = 10^{-3}$ for 20 epochs. -
Stage 2 (Fine-Tuning): Unfroze
layer4with differential learning rates ($\text{LR} = 10^{-5}$ for backbone,$\text{LR} = 10^{-4}$ for head) with early stopping.
-
Stage 1 (Warmup): Frozen backbone, training the linear head at
-
BatchNorm Protection: Fixed BatchNorm running statistics during fine-tuning (
freeze_bn) to prevent batch statistics drift on small mini-batches.
Solar-Panel-Defect-Classification/
├── .github/
│ └── workflows/
│ └── ci.yml # GitHub Actions CI workflow (automated pytest runs)
├── .dockerignore # Excludes data/, notebooks/, and cache from builds
├── .gitignore
├── Dockerfile # Containerized deployment specification
├── pyproject.toml # Project dependencies and tool configurations
├── requirements.txt # Pinned python packages
├── README.md # Comprehensive project documentation
├── train.py # PyTorch training & fine-tuning pipeline
├── export_onnx.py # Exports PyTorch weights to ONNX with parity verification
├── benchmark.py # Compares PyTorch vs ONNX Runtime CPU latency
├── app.py # Streamlit web application with Grad-CAM visualization
├── models/ # Saved model artifacts (.pt / .onnx - gitignored)
├── plots/
│ └── confusion_matrix.png # Confusion matrix visualization
├── src/ # Modular source code
│ ├── dataset.py # Dataset class, transforms, and augmentation
│ ├── model.py # SolarResNet architecture definition
│ ├── engine.py # Training and validation step loops
│ └── explainability.py # Grad-CAM engine and heatmap blending logic
└── tests/ # Automated test suite
├── __init__.py
└── test_pipeline.py # 9 unit & integration tests
# Clone the repository
git clone https://github.com/paras-the-coder/Solar-Panel-Defect-Classification.git
cd Solar-Panel-Defect-Classification
# Create and activate virtual environment
python -m venv venv
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txtpytest -v tests/# Export trained checkpoint to ONNX
python export_onnx.py
# Benchmark PyTorch vs ONNX Runtime CPU latency
python benchmark.py --iterations 100streamlit run app.py# Build Docker image
docker build -t solar-defect-classifier .
# Run container
docker run -p 8501:8501 solar-defect-classifierNavigate to http://localhost:8501 in your browser.
- PyTorch modular training and evaluation pipeline
- Grad-CAM visual heatmaps for transparent defect localization
- ONNX Runtime export and CPU latency profiling
- Automated unit test suite with GitHub Actions CI
- Fast bounding-box defect localization via YOLOv11 for whole-array drone orthomosaics
- Asynchronous FastAPI backend microservice decoupled from Streamlit frontend