Transfer Learning for Building Detection from Sentinel Imagery
EU-Philippines CoPhil Programme
Duration: 2.5 hours Type: Hands-on Coding Lab Platform: Google Colab with GPU
You will:
Prerequisites:
Resources:
Day3_Session4_Object_Detection_STUDENT.ipynbLocation: Metro Manila - National Capital Region (NCR) Focus Areas: Quezon City and Pasig River corridor Challenge: Rapid informal settlement growth and urban sprawl
Why This Matters
Metro Manila’s rapid urbanization creates challenges for:
Data Source: Sentinel-2 Multispectral Imagery
Lab Goal:
Automate building detection using transfer learning to enable rapid, scalable urban monitoring
7 Key Steps:
Definition: Adapt a model pre-trained on a large dataset to your specific task with minimal additional training data
Analogy: Like a doctor specializing in cardiology after completing general medical training - the foundational knowledge transfers, requiring less time to specialize
Trained on: COCO dataset (330K images, 80 classes)
Fine-tune with: 100-500 labeled satellite images
. . .
| Model | Speed | Accuracy | Best For |
|---|---|---|---|
| SSD MobileNet V2 | Fast | Good | Real-time applications, resource-constrained |
| Faster R-CNN ResNet50 | Slow | Excellent | Offline analysis, high accuracy priority |
| YOLO v5/v8 | Moderate | Very Good | Balanced speed and accuracy |
Recommendation for Lab
We’ll use SSD MobileNet V2 - fast training, good accuracy, works well with Sentinel-2 imagery
Objective: Load a pre-trained object detector from TensorFlow Hub
What You’ll Learn:
Objective: Load and prepare satellite imagery with building annotations
Data Format:
Images:
Annotations:
Steps:
Demo Data Included
For this lab, we provide ready-to-use Metro Manila satellite patches with pre-annotated buildings. No lengthy data collection required!
Objective: Adapt the pre-trained detector to recognize buildings in satellite imagery
Fine-tuning Strategy:
# Configure optimizer
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001)
# Training loop
for epoch in range(20):
for batch_images, batch_boxes in train_dataset:
with tf.GradientTape() as tape:
# Forward pass
predictions = model(batch_images, training=True)
# Calculate loss (classification + localization)
loss = detection_loss(predictions, batch_boxes)
# Backpropagation
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# Validation
val_loss = evaluate(model, val_dataset)
print(f"Epoch {epoch}: Train Loss={loss:.4f}, Val Loss={val_loss:.4f}")Training Progress:
Signs of Good Training:
Objective: Calculate mean Average Precision - the standard object detection metric
Precision: Of detected buildings, how many are correct?
\[\text{Precision} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Positives}}\]
Recall: Of all actual buildings, how many did we detect?
\[\text{Recall} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Negatives}}\]
Average Precision (AP):
mAP (mean Average Precision):
Intersection over Union (IoU):
\[\text{IoU} = \frac{\text{Area of Overlap}}{\text{Area of Union}}\]
Common Thresholds:
For This Lab
We’ll use mAP@0.5 - more lenient, suitable for satellite imagery where exact boundaries are challenging
# Evaluate on test set
from object_detection.utils import object_detection_evaluation
evaluator = object_detection_evaluation.ObjectDetectionEvaluator(
categories=[{"id": 1, "name": "building"}]
)
for test_image, test_boxes in test_dataset:
detections = model(test_image)
evaluator.add_single_ground_truth_image_info(test_boxes)
evaluator.add_single_detected_image_info(detections)
results = evaluator.evaluate()
print(f"mAP@0.5: {results['mAP_50']:.3f}")
print(f"Precision: {results['precision']:.3f}")
print(f"Recall: {results['recall']:.3f}")| Phase | mAP@0.5 | Interpretation |
|---|---|---|
| Before fine-tuning | 0.10-0.20 | Pre-trained on natural images, not adapted for buildings |
| After fine-tuning | 0.70-0.85 | Operational quality, suitable for urban monitoring |
| Production target | >0.80 | High confidence for decision-making |
Performance Depends On
Objective: Visualize model predictions on Metro Manila satellite imagery
Tasks:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Load test image
image = load_satellite_image("metro_manila_test_001.tif")
detections = model.predict(image)
# Create figure
fig, ax = plt.subplots(1, figsize=(12, 12))
ax.imshow(image)
# Draw bounding boxes
for det in detections:
if det['score'] > 0.5: # Confidence threshold
x, y, w, h = det['bbox']
rect = patches.Rectangle((x, y), w, h,
linewidth=2, edgecolor='red',
facecolor='none')
ax.add_patch(rect)
ax.text(x, y-5, f"Building {det['score']:.2f}",
color='red', fontsize=10,
bbox=dict(facecolor='white', alpha=0.7))
plt.title("Building Detection - Metro Manila")
plt.axis('off')
plt.show()Quantitative:
Qualitative:
Application: Identify unplanned settlements in flood-prone areas Stakeholder: NDRRMC, Local Government Units (LGUs) Output: Building density maps, population estimates
Workflow:
Application: Track new construction over time Method: Compare detections from multi-temporal imagery Output: Change maps showing urban expansion hotspots
Process:
Application: Post-typhoon damage assessment Method: Detect changes in building footprints Output: Damage severity maps for relief operations
Indicators:
Application: Identify under-served areas Stakeholder: DPWH, MMDA Output: Priority areas for infrastructure development
Analysis:
1. Automated Data Acquisition
2. Pre-processing
3. Inference
4. Post-processing
5. GIS Export
1. Acquire Satellite Imagery:
2. Create Annotations:
3. Annotation Guidelines:
4. Validation:
| Challenge | Solution |
|---|---|
| Dense urban areas | Use higher resolution imagery (Pléiades, SPOT 6/7) |
| Cloud cover | Combine Sentinel-2 optical with Sentinel-1 SAR |
| Small buildings | Use models optimized for small objects (YOLO v8) |
| Shadow confusion | Include shadow-augmented training data |
| Computation cost | Use lighter models (MobileNet) or cloud GPUs |
| Activity | Duration | Notes |
|---|---|---|
| Introduction & Setup | 15 min | GPU check, notebook familiarization |
| Load Pre-trained Model | 20 min | TensorFlow Hub, test inference |
| Data Preparation | 30 min | Load data, visualize, split |
| Fine-tuning | 40 min | Training loop, monitor loss |
| Evaluation | 25 min | Calculate mAP, interpret metrics |
| Visualization | 20 min | Plot detections, analyze results |
| Export & Integration | 10 min | GeoJSON export, GIS demo |
| Troubleshooting | 10 min | Address common issues |
| Buffer | 10 min | Q&A, extensions |
| Total | 150 min | 2.5 hours |
Issue 1: Out of Memory (OOM)
Issue 2: mAP Very Low (<0.30)
Issue 3: Detects Everything as Buildings
Issue 4: Training Very Slow
!nvidia-smi to verify GPU allocationKey Achievements
✅ Loaded and understood pre-trained object detection models ✅ Prepared satellite imagery and COCO annotations ✅ Fine-tuned detector on urban building dataset ✅ Evaluated performance using mAP metrics ✅ Visualized detections on Metro Manila imagery ✅ Connected to real-world Philippine urban monitoring ✅ Understood deployment pipeline for operations
| Aspect | Session 2 (Segmentation) | Session 4 (Detection) |
|---|---|---|
| Task | Pixel-wise classification | Object localization + classification |
| Output | Binary flood mask | Bounding boxes + labels |
| Metric | IoU, F1-score, Dice | mAP, Precision, Recall |
| Use Case | Flood extent mapping | Building counting, urban growth |
| Data | Sentinel-1 SAR | Sentinel-2 Optical |
| Granularity | Every pixel labeled | Objects with boxes |
Both are complementary!
Apply This Workflow:
Advanced Extensions:
Advanced Exercise 1: Multi-class Detection
Advanced Exercise 2: Change Detection
Advanced Exercise 3: Anchor Box Optimization
By the end of this lab, you should be able to:
Object detection with transfer learning is a powerful and practical tool for Earth observation applications.
Key Benefits:
Final Message:
Even small teams with limited resources can build production-quality detectors for critical applications like disaster preparedness and urban planning!
Open the Notebook and Begin!
📓 Day3_Session4_Object_Detection_STUDENT.ipynb
Estimated completion: 2-2.5 hours
Questions? Ask your instructor during the session.
Questions?
Contact:
Let’s build urban monitoring solutions for the Philippines!
Session 4: Hands-on Object Detection Lab - CoPhil 4-Day Advanced Training on AI/ML for Earth Observation, funded by the European Union under the Global Gateway initiative.

DAY 3 - Session 4 | Object Detection Lab | 20-23 October 2025