RoI Align and the classification and box-regression heads.
ROI Head: ROI Align + Classification and Box Regression
Section 4 of 6 in the Faster RCNN from-scratch seriesGiven proposals from the RPN, we extract fixed-size features via ROI Align,
then classify each proposal and refine its bounding box.Mask RCNN extension point: this section also demonstrates the 14×14
ROI Align variant used by the mask head (section 07).
Code
import sys, os, pathlib# Locate frcnn_common.py, works whether run via papermill or interactively_nb_candidates = [ pathlib.Path.cwd().parent, # interactive: cwd is the notebook dir pathlib.Path.cwd() / 'notebooks' / 'scene-understanding' / 'object-detection' / 'faster-rcnn' / 'pytorch', # papermill: cwd is repo root]for _p in _nb_candidates: if (_p / 'frcnn_common.py').exists(): sys.path.insert(0, str(_p)) breakimport torchimport torch.nn as nnimport torch.nn.functional as Fimport matplotlib.pyplot as pltfrom cycler import cyclerfrom matplotlib_inline.backend_inline import set_matplotlib_formatsset_matplotlib_formats("svg")FIG_GRAY = "#808080"FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]plt.rcParams.update({ "figure.facecolor": "none", "axes.facecolor": "none", "savefig.facecolor": "none", "savefig.transparent": True, "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY, "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY, "grid.color": FIG_GRAY, "grid.alpha": 0.25, "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0, "axes.prop_cycle": cycler(color=FIG_COLORS), "svg.hashsalt": "aiml", "svg.fonttype": "path",})from typing import List, Tuplefrom frcnn_common import ( ROIAlign, TwoMLPHead, FastRCNNPredictor, Bottleneck, ResNet50, FPN, AnchorGenerator, RPNHead, RegionProposalNetwork, IMG_SIZE, DEVICE,)print(f"Device: {DEVICE}")
/workspaces/eng-ai-agents/.venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
Device: cuda
Code
# ROIAlign is imported from frcnn_common, inspect its structure:roi_align = ROIAlign(out_size=7)print(f"ROI output size: {roi_align.out_size}")print(f"FPN level params: k0={roi_align.k0}, k_min={roi_align.k_min}, k_max={roi_align.k_max}")
ROI output size: 7FPN level params: k0=4, k_min=2, k_max=5
Code
# TwoMLPHead and FastRCNNPredictor are imported from frcnn_common:mlp_head = TwoMLPHead()predictor = FastRCNNPredictor()print("TwoMLPHead:", mlp_head)print("FastRCNNPredictor:", predictor)