Panduan Lengkap DETR: Object Detection dengan Transformers
DETR (DEtection TRansformer) adalah pendekatan revolusioner untuk object detection yang dikembangkan oleh Facebook AI Research. DETR menggantikan pipeline tradisional yang kompleks dengan arsitektur Transformer yang elegan dan end-to-end.
Dalam tutorial ini, kita akan mempelajari DETR dari konsep dasar hingga implementasi praktis untuk object detection dan segmentation.
Mengapa DETR?
Keunggulan DETR:
Perbandingan dengan Metode Tradisional:
| Aspek | Traditional (Faster R-CNN) | DETR |
|-------|---------------------------|------|
| Anchor Boxes | Ya | Tidak |
| NMS Post-processing | Ya | Tidak |
| Hand-crafted Components | Banyak | Minimal |
| End-to-End Training | Tidak | Ya |
| Global Context | Terbatas | Penuh |
Arsitektur DETR
Komponen Utama:
Input Image → CNN Backbone → Transformer Encoder → Transformer Decoder → FFN → Predictions
↓ ↓ ↓
Features Positional Object Queries
Encoding (Learned)
1. CNN Backbone
# ResNet-50 atau ResNet-101 sebagai feature extractor
Input: Image (3, H, W)
Output: Feature map (2048, H/32, W/32)
2. Transformer Encoder
# Memproses flattened feature map dengan self-attention
Menambahkan positional encoding
Output: Encoded features dengan global context
3. Transformer Decoder
# Menggunakan learned object queries (default: 100)
Cross-attention dengan encoded features
Self-attention antar object queries
Output: 100 embeddings untuk prediksi
4. Prediction Heads
# FFN untuk class prediction
FFN untuk bounding box prediction (centerx, centery, width, height)
Special class: "no object" untuk query yang tidak mendeteksi objek
Instalasi
Requirements
# Clone repository
git clone https://github.com/facebookresearch/detr.git
cd detr
Install dependencies
conda create -n detr python=3.8
conda activate detr
PyTorch dan Torchvision
conda install pytorch torchvision cudatoolkit=11.3 -c pytorch
Dependencies lainnya
conda install cython scipy
pip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'
Untuk panoptic segmentation (optional)
pip install git+https://github.com/cocodataset/panopticapi.git
Verifikasi Instalasi
import torch
import torchvision
print(f"PyTorch version: {torch.version}")
print(f"Torchvision version: {torchvision.version}")
print(f"CUDA available: {torch.cuda.isavailable()}")
Quick Start: Inference dengan Pretrained Model
1. Load Model via PyTorch Hub
import torch
from PIL import Image
import requests
import matplotlib.pyplot as plt
Load pretrained DETR model
model = torch.hub.load('facebookresearch/detr:main', 'detrresnet50', pretrained=True)
model.eval()
COCO classes
CLASSES = [
'N/A', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',
'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack',
'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',