- Project Overview
- Why From Scratch?
- Complete Architecture
- Component Breakdown
- Training vs Inference Flow
- Data Flow Pipeline
- Key Features
- Technical Stack
- Quick Start
- Project Structure
- Learning Outcomes
- License & Acknowledgments
Mask R-CNN From Scratch is a complete, production-ready implementation of the state-of-the-art Mask R-CNN architecture built entirely from the ground up using TensorFlow/Keras. Unlike other implementations that import pre-built ResNet or pre-trained models, every single layer is defined and built from scratch, giving you complete control and understanding of the entire architecture.
| Aspect | Details |
|---|---|
| Type | Object Detection + Instance Segmentation |
| Implementation | 100% From Scratch (No imported models) |
| Framework | TensorFlow 2.14+ / Keras |
| Backbone | ResNet50/101 (Built from layers) |
| Architecture | ResNet + FPN + RPN + ROI Align + Heads |
| Reason | Benefit |
|---|---|
| Complete Control | Modify any layer without framework limitations |
| Full Transparency | Understand every operation in the pipeline |
| Educational Value | Learn Mask R-CNN internals by building them |
| Flexibility | Add custom layers, losses, or modifications easily |
| No Black Boxes | Everything is visible and debuggable |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β MASK R-CNN COMPLETE ARCHITECTURE β β (Built 100% From Scratch) β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β β β INPUT IMAGE [batch, H, W, 3] β β β β β βΌ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β STEP 1: RESNET BACKBONE (resnet_graph) ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β Stage 1: Conv7x7 + MaxPool β C1 [256x256x64] β ββ β β β Stage 2: Conv + 2x Identity β C2 [256x256x256] β Fine details β ββ β β β Stage 3: Conv + 3x Identity β C3 [128x128x512] β Object parts β ββ β β β Stage 4: Conv + 5/22x Identity β C4 [64x64x1024] β Whole objects β ββ β β β Stage 5: Conv + 2x Identity β C5 [32x32x2048] β Semantic context β ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β βΌ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β STEP 2: FPN CONSTRUCTION (build() method) ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β C5 β Conv1x1 β P5 [32x32x256] β Largest objects β ββ β β β C4 β Conv1x1 + Upsample(P5) β P4 [64x64x256] β Large objects β ββ β β β C3 β Conv1x1 + Upsample(P4) β P3 [128x128x256] β Medium objects β ββ β β β C2 β Conv1x1 + Upsample(P3) β P2 [256x256x256] β Small objects β ββ β β β P5 β MaxPool β P6 [16x16x256] β Extra large (RPN only) β ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β βΌ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β STEP 3: RPN (rpn_graph) ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β For each P2-P6: β ββ β β β Shared Conv3x3(512) β Branch β ββ β β β βββ Classification Head: Conv1x1(2A) β rpn_class_logits [batch, total_anchors, 2] β ββ β β β βββ BBox Head: Conv1x1(4A) β rpn_bbox [batch, total_anchors, 4] β ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β βΌ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β STEP 4: PROPOSAL LAYER (ProposalLayer) ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β 1. Select top 6000 anchors by FG score β ββ β β β 2. apply_box_deltas_graph() β Refine boxes β ββ β β β 3. clip_boxes_graph() β Clip to [0,1] β ββ β β β 4. NMS β Keep top 2000 (training) or 1000 (inference) β ββ β β β Output: rpn_rois [batch, 2000/1000, 4] β ββ β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β β β β βΌ βΌ β β βββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β TRAINING PATH β β INFERENCE PATH ββ β β ββββββββββββββββββββββββββββββββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β DetectionTargetLayer ββ β β Heads (Direct from rpn_rois) β ββ β β β Inputs: rpn_rois + GT ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β 1. IoU Computation ββ β β ββ β β β 2. Classify proposals ββ β βΌ ββ β β β 3. Subsample to 200 ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β 4. Generate targets ββ β β DetectionLayer β ββ β β β Outputs: ββ β β 1. Get best class (argmax) β ββ β β β - rois [200,4] ββ β β 2. Class-specific deltas β ββ β β β - target_class_ids [200] ββ β β 3. Refine boxes β ββ β β β - target_bbox [200,4] ββ β β 4. Filter background + confidence β ββ β β β - target_mask [200,28,28]ββ β β 5. Class-wise NMS β ββ β β ββββββββββββββββββββββββββββββββ β β Output: detections [max, 6] β ββ β β β β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β βΌ β β β ββ β β ββββββββββββββββββββββββββββββββ β βΌ ββ β β β PyramidROIAlign (7x7/14x14)ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β 1. Assign to FPN level ββ β β build_fpn_mask_graph() β ββ β β β 2. Crop features ββ β β detection_boxes + P2-P5 β masks β ββ β β β 3. Resize to fixed size ββ β β Output: mrcnn_mask [max, 28, 28, C] β ββ β β ββββββββββββββββββββββββββββββββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β β β β ββ β β βΌ β β βΌ ββ β β ββββββββββββββββββββββββββββββββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β fpn_classifier_graph() ββ β β FINAL OUTPUT β ββ β β β ROI features (7x7) β ββ β β detections + mrcnn_mask β ββ β β β 2x FC Layers β ββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β β β βββ Classifier Head (C) ββ β ββ β β β βββ BBox Head (C,4) ββ β ββ β β ββββββββββββββββββββββββββββββββ β ββ β β β β β ββ β β βΌ β β ββ β β ββββββββββββββββββββββββββββββββ β ββ β β β build_fpn_mask_graph() ββ β ββ β β β ROI features (14x14) β ββ β ββ β β β 4x Conv3x3 β ββ β ββ β β β Deconv(28x28) β ββ β ββ β β β Conv1x1 + Sigmoid ββ β ββ β β β Output: mrcnn_mask [C] ββ β ββ β β ββββββββββββββββββββββββββββββββ β ββ β β β β β ββ β β βΌ β β ββ β β ββββββββββββββββββββββββββββββββ β ββ β β β LOSS FUNCTIONS ββ β ββ β β β 1. rpn_class_loss ββ β ββ β β β 2. rpn_bbox_loss ββ β ββ β β β 3. mrcnn_class_loss ββ β ββ β β β 4. mrcnn_bbox_loss ββ β ββ β β β 5. mrcnn_mask_loss ββ β ββ β β ββββββββββββββββββββββββββββββββ β ββ β βββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Stage | Blocks | Output Shape | Purpose |
|---|---|---|---|
| Stage 1 | Conv7x7 + MaxPool | 256Γ256Γ64 | Initial feature extraction |
| Stage 2 | Conv + 2x Identity | 256Γ256Γ256 | Fine details, edges |
| Stage 3 | Conv + 3x Identity | 128Γ128Γ512 | Object parts, textures |
| Stage 4 | Conv + 5/22x Identity | 64Γ64Γ1024 | Whole objects, structures |
| Stage 5 | Conv + 2x Identity | 32Γ32Γ2048 | Semantic concepts, context |
Key Components:
identity_block: Skip connection, no shape changeconv_block: Skip connection with Conv1x1, changes shape- Both blocks have the SAME main path, only shortcut differs
| Level | Resolution | Used For |
|---|---|---|
| P2 | 256Γ256 | Small objects (fine details) |
| P3 | 128Γ128 | Medium objects |
| P4 | 64Γ64 | Large objects |
| P5 | 32Γ32 | Very large objects (semantic) |
| P6 | 16Γ16 | RPN only (extra large) |
Process:
- Lateral Connections: Conv1x1 on C2-C5 β 256 channels
- Top-Down Pathway: Upsample + Add β Combine features
- Smoothing: Conv3x3 on each P layer
| Component | Purpose | Output Shape |
|---|---|---|
| Shared Conv | Feature extraction | [batch, H, W, 512] |
| Classification Head | FG vs BG scores | [batch, total_anchors, 2] |
| BBox Head | Anchor refinements | [batch, total_anchors, 4] |
- Input: P2-P6 feature maps
- Output: rpn_class_logits, rpn_probs, rpn_bbox
- Anchors: ~785,000 (5 scales Γ 3 ratios per pixel)
| Step | Operation | Output |
|---|---|---|
| 1 | Select top 6000 by FG score | 6000 anchors |
| 2 | Apply deltas (apply_box_deltas_graph) |
6000 refined boxes |
| 3 | Clip to image (clip_boxes_graph) |
6000 clipped boxes |
| 4 | NMS (IoU > 0.7) | 2000/1000 proposals |
Output: rpn_rois [batch, proposal_count, 4]
| Step | Operation | Purpose |
|---|---|---|
| 1 | Remove padding | Clean data |
| 2 | Handle COCO crowds | Exclude crowds |
| 3 | Compute IoU | Match proposals to GT |
| 4 | Classify proposals | Positive (IoUβ₯0.5) / Negative (IoU<0.5) |
| 5 | Subsample to 200 | 33% positive, 67% negative |
| 6 | Generate targets | Class IDs, bbox deltas, masks |
Output: rois [200,4], target_class_ids [200], target_bbox [200,4], target_mask [200,28,28]
| Step | Operation | Purpose |
|---|---|---|
| 1 | Calculate area | Determine proposal size |
| 2 | Assign to FPN level | P2 (small), P3 (medium), P4 (large), P5 (very large) |
| 3 | Crop features | Extract from correct level |
| 4 | Resize to fixed size | 7Γ7 (classifier) or 14Γ14 (mask) |
| 5 | Bilinear interpolation | No quantization error |
Output: [batch, num_rois, 7/14, 7/14, 256]
| Layer | Input | Output | Purpose |
|---|---|---|---|
| ROI Align (7Γ7) | rois [200,4] |
[200,7,7,256] |
Extract features |
| FC Layer 1 | [200,7,7,256] |
[200,1,1,1024] |
Feature transformation |
| FC Layer 2 | [200,1,1,1024] |
[200,1,1,1024] |
Feature transformation |
| Squeeze | [200,1,1,1024] |
[200,1024] |
Flatten |
| Classifier Head | [200,1024] |
[200,C] |
Predict class |
| BBox Head | [200,1024] |
[200,C,4] |
Predict deltas per class |
Outputs: mrcnn_class_logits, mrcnn_probs, mrcnn_bbox
| Layer | Input | Output | Purpose |
|---|---|---|---|
| ROI Align (14Γ14) | rois [200,4] |
[200,14,14,256] |
Extract detailed features |
| Conv1-4 | [200,14,14,256] |
[200,14,14,256] |
Feature learning |
| Deconv | [200,14,14,256] |
[200,28,28,256] |
Upsample to 28Γ28 |
| Conv1Γ1 + Sigmoid | [200,28,28,256] |
[200,28,28,C] |
Predict per-class masks |
Output: mrcnn_mask [batch, 200, 28, 28, C]
| Step | Operation | Purpose |
|---|---|---|
| 1 | Get best class (argmax) | Choose class per proposal |
| 2 | Get class-specific deltas | Refine box for that class |
| 3 | Apply deltas | Refine boxes |
| 4 | Filter background | Remove class=0 |
| 5 | Filter low confidence | Remove low scores |
| 6 | Class-wise NMS | Remove duplicates per class |
| 7 | Pad to fixed size | Consistent output shape |
Output: detections [batch, max_instances, 6]
| Loss | Type | Purpose |
|---|---|---|
| RPN Class | Cross Entropy | Learn which anchors have objects |
| RPN BBox | Smooth L1 | Refine anchor boxes |
| MRCNN Class | Sparse Cross Entropy | Predict correct class |
| MRCNN BBox | Smooth L1 | Refine boxes per class |
| MRCNN Mask | Binary Cross Entropy | Predict accurate masks |
Image + GT β ResNet β FPN β RPN β Proposals (2000) β βΌ DetectionTargetLayer β rois (200) + targets β βΌ ROI Align β ROI features (7x7, 14x14) β βΌ Heads β Predictions (class, bbox, mask) β βΌ Loss Functions β Backpropagation β Update ALL weights
text
Image β ResNet β FPN β RPN β Proposals (1000) β βΌ ROI Align β ROI features (7x7, 14x14) β βΌ Heads β Predictions (class, bbox, mask) β βΌ DetectionLayer β Final detections (boxes, classes, scores, masks)
text
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β COMPLETE DATA FLOW β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β β β DATASET β β βββ Images + Annotations (boxes, classes, masks) β β β β β βΌ β β DataGenerator.getitem() β β βββ load_image_gt() β Image + GT (resized, augmented) β β βββ build_rpn_targets() β rpn_match + rpn_bbox β β βββ Returns: [images, image_meta, rpn_match, rpn_bbox, gt_class_ids, gt_boxes, gt_masks] β β β β β βΌ β β MODEL.TRAIN() β β βββ ResNet β C2, C3, C4, C5 β β βββ FPN β P2, P3, P4, P5, P6 β β βββ RPN β rpn_class, rpn_bbox β β βββ ProposalLayer β rpn_rois (2000/1000) β β βββ DetectionTargetLayer β rois (200) + targets β β βββ ROI Align β ROI features (7Γ7, 14Γ14) β β βββ Heads β Predictions β β βββ Loss β Compare predictions to targets β β βββ Backpropagation β Update weights β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Feature | Description |
|---|---|
| Bounding Box Detection | Accurate localization with class labels |
| Instance Segmentation | Pixel-perfect masks for each object |
| Multi-Object Detection | Detect multiple objects of different classes |
| Confidence Scoring | Probability score for each detection |
| Feature | Description |
|---|---|
| End-to-End Training | Train all components together |
| Multi-GPU Support | Parallel training across GPUs |
| Custom Dataset Support | Easy integration with your own data |
| Data Augmentation | Built-in augmentation pipeline |
| Transfer Learning | Pre-trained ImageNet weights support |
tensorflow-macos==2.14.0 # TensorFlow for M1 Mac
tensorflow-metal==1.0.1 # GPU acceleration for M1
keras==2.14.0 # High-level API
numpy==1.23.5 # Numerical operations
opencv-python==4.8.0.76 # Image operations
matplotlib==3.7.1 # Visualization
scipy==1.11.3 # Scientific computing
h5py==3.9.0 # HDF5 file handling
imgaug==0.4.0 # Data augmentation
Hardware Requirements
Component Minimum Recommended
GPU 8GB VRAM 12GB+ VRAM
RAM 16GB 32GB+
Storage 50GB 100GB+
CPU 4 cores 8+ cores
Installation
# 1. Create environment
conda create -n maskrcnn python=3.11
conda activate maskrcnn
# 2. Install TensorFlow (M1 Mac)
conda install -c apple tensorflow-deps
pip install tensorflow-macos==2.14.0 tensorflow-metal==1.0.1
# 3. Install dependencies
pip install -r requirements.txt
# 4. Clone repository
git clone https://github.com/yourusername/mask-rcnn-from-scratch.git
cd mask-rcnn-from-scratch
Inference
python
# 1. Create inference model
inference_model = MaskRCNN(mode='inference', config=config, model_dir='./logs')
inference_model.load_weights('path/to/weights.h5', by_name=True)
# 2. Detect
image = cv2.imread('test.jpg')
results = inference_model.detect([image])
# 3. Visualize
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'],
r['class_ids'], class_names, r['scores'])
π Project Structure
text
mask-rcnn-from-scratch/
β
βββ README.md # This file
βββ requirements.txt # Dependencies
β
βββ mrcnn/ # Core package
β βββ model.py # Main implementation (3000+ lines)
β βββ utils.py # Utility functions
β βββ config.py # Configuration classes
β βββ parallel_model.py # Multi-GPU support
β
βββ examples/ # Example notebooks
β βββ train.ipynb # Training example
β βββ inference.ipynb # Inference example
β
βββ logs/ # Training logs
β βββ mask_rcnn_YYYYMMDDTHHMM/ # Model checkpoints
β
βββ weights/ # Pre-trained weights
βββ mask_rcnn_coco.h5 # COCO pre-trained
π Learning Outcomes
By studying this implementation, you will understand:
Concept What You'll Learn
ResNet Architecture How identity and conv blocks work together
Feature Pyramid Networks Multi-scale feature extraction
Region Proposal Networks Anchor-based object proposal generation
ROI Align Precise feature extraction without quantization
Instance Segmentation Pixel-perfect mask prediction
End-to-End Training How all components train together
Loss Functions Multi-task learning with 5 losses
Data Pipeline Efficient data loading and augmentation
π License & Acknowledgments
License
MIT License - See LICENSE file for details.
Acknowledgments
Original Implementation: Matterport Mask R-CNN by Waleed Abdulla
Research Paper: Mask R-CNN by Kaiming He et al.
ResNet Code: Adapted from fchollet/deep-learning-models
π If you find this project useful, please give it a star on GitHub!