Detectron2 Tutorial: Object Detection & Segmentation Framework

# Detectron2 - Deteksi Objek dan Segmentasi ## Daftar Isi 1. [Pendahuluan](#pendahuluan) 2. [Prasyarat](#prasyarat) 3. [Instalasi](#instalasi) 4. [Memahami Arsitektur Detectron2](#memahami-arsitektu...

By Ruby Abdullah · · tutorial
Detectron2Object DetectionInstance SegmentationPanopticCOCOFacebook AI

Detectron2 - Object Detection and Segmentation

Table of Contents

  • Introduction
  • Prerequisites
  • Installation
  • Understanding Detectron2 Architecture
  • Using Pre-trained Models
  • Instance Segmentation
  • Semantic Segmentation
  • Panoptic Segmentation
  • Preparing Custom Datasets in COCO Format
  • Training on Custom Datasets
  • The Config System
  • Model Zoo
  • Evaluation Metrics
  • Deployment
  • Best Practices
  • Conclusion

  • Introduction

    Detectron2 is Facebook AI Research's (FAIR) next-generation library for object detection, instance segmentation, and other visual recognition tasks. Built on top of PyTorch, it provides a modular and extensible framework that powers many state-of-the-art computer vision models.

    Key features of Detectron2:

    • Modular design: Easily swap backbones, heads, and other components
    • Rich Model Zoo: Pre-trained models for detection, segmentation, keypoint detection, and more
    • High performance: Optimized training and inference with multi-GPU support
    • Flexible config system: YAML-based configuration with full Python override capability
    • Production-ready: Export to TorchScript, ONNX, and Caffe2 for deployment

    In this tutorial, you will learn to use Detectron2 for object detection and segmentation tasks, train on custom datasets, navigate the config system, and deploy models to production.


    Prerequisites

    • Python 3.7 or higher
    • PyTorch 1.9+ with CUDA support (GPU strongly recommended)
    • Basic understanding of object detection and segmentation concepts
    • Familiarity with COCO dataset format
    • Linux operating system (recommended; macOS and Windows have limited support)


    Installation

    # Install PyTorch first (check pytorch.org for your CUDA version)
    

    pip install torch torchvision

    Install Detectron2

    pip install 'git+https://github.com/facebookresearch/detectron2.git'

    Alternative: install from pre-built wheels (faster)

    Check https://detectron2.readthedocs.io/en/latest/tutorials/install.html

    pip install detectron2 -f \

    https://dl.fbaipublicfiles.com/detectron2/wheels/cu118/torch2.0/index.html

    Additional dependencies

    pip install opencv-python pillow matplotlib

    Verify the installation:

    import detectron2
    

    from detectron2.utils.logger import setuplogger

    setuplogger()

    print(f"Detectron2 version: {detectron2.version}")

    import torch

    print(f"PyTorch version: {torch.version}")

    print(f"CUDA available: {torch.cuda.isavailable()}")

    print(f"CUDA version: {torch.version.cuda}")


    Understanding Detectron2 Architecture

    Detectron2 follows a modular architecture with these key components:

    Input Image
    

    |

    v

    [Backbone] --> Feature Maps (FPN)

    |

    v

    [Region Proposal Network (RPN)] --> Proposals

    |

    v

    [ROI Heads] --> Detections, Masks, Keypoints

    |

    v

    [Post-processing] --> Final Predictions

    Core abstractions:

    from detectron2.modeling import buildmodel
    

    from detectron2.config import getcfg

    The config defines the entire model architecture

    cfg = getcfg()

    Key components:

    - cfg.MODEL.BACKBONE: Feature extractor (ResNet, ResNeXt, etc.)

    - cfg.MODEL.FPN: Feature Pyramid Network settings

    - cfg.MODEL.RPN: Region Proposal Network

    - cfg.MODEL.ROIHEADS: Detection/segmentation heads

    - cfg.MODEL.PIXELMEAN/STD: Input normalization


    Using Pre-trained Models

    The fastest way to start is with pre-trained models from Model Zoo.

    import cv2
    

    import numpy as np

    from detectron2 import modelzoo

    from detectron2.engine import DefaultPredictor

    from detectron2.config import getcfg

    from detectron2.utils.visualizer import Visualizer

    from detectron2.data import MetadataCatalog

    def setuppredictor(configpath, threshold=0.5):

    """Set up a Detectron2 predictor with a pre-trained model."""

    cfg = getcfg()

    cfg.mergefromfile(modelzoo.getconfigfile(configpath))

    cfg.MODEL.WEIGHTS = modelzoo.getcheckpointurl(configpath)

    cfg.MODEL.ROIHEADS.SCORETHRESHTEST = threshold

    cfg.MODEL.DEVICE = "cuda" if torch.cuda.isavailable() else "cpu"

    predictor = DefaultPredictor(cfg)

    return predictor, cfg

    Object detection with Faster R-CNN

    predictor, cfg = setuppredictor(

    "COCO-Detection/fasterrcnnR50FPN3x.yaml",

    threshold=0.5

    )

    Run inference

    image = cv2.imread("testimage.jpg")

    outputs = predictor(image)

    Access predictions

    instances = outputs["instances"]

    print(f"Detected {len(instances)} objects")

    print(f"Classes: {instances.predclasses}")

    print(f"Scores: {instances.scores}")

    print(f"Bounding boxes: {instances.predboxes}")

    Visualize results

    v = Visualizer(

    image[:, :, ::-1], # BGR to RGB

    MetadataCatalog.get(cfg.DATASETS.TRAIN[0]),

    scale=1.0

    )

    outputvis = v.drawinstancepredictions(instances.to("cpu"))

    resultimage = outputvis.getimage()[:, :, ::-1] # RGB to BGR

    cv2.imwrite("detectionresult.jpg", resultimage)


    Instance Segmentation

    Instance segmentation detects objects and produces a pixel-level mask for each instance.

    # Instance segmentation with Mask R-CNN
    

    predictor, cfg = setuppredictor(

    "COCO-InstanceSegmentation/maskrcnnR50FPN3x.yaml",

    threshold=0.5

    )

    image = cv2.imread("streetscene.jpg")

    outputs = predictor(image)

    instances = outputs["instances"]

    print(f"Number of instances: {len(instances)}")

    Access instance masks

    masks = instances.predmasks # Shape: (N, H, W) boolean tensor

    boxes = instances.predboxes

    classes = instances.predclasses

    scores = instances.scores

    Extract individual object masks

    for i in range(len(instances)):

    mask = masks[i].cpu().numpy() # Boolean mask for this instance

    cls = classes[i].item()

    score = scores[i].item()

    classname = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).thingclasses[cls]

    print(f" Instance {i}: {classname} (confidence: {score:.3f}), "

    f"mask pixels: {mask.sum()}")

    Visualize

    v = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]))

    outputvis = v.drawinstancepredictions(instances.to("cpu"))

    cv2.imwrite("instancesegmentation.jpg", outputvis.getimage()[:, :, ::-1])

    Extract and save individual object crops with masks

    def extractmaskedobjects(image, instances, outputdir="objects"):

    """Extract individual objects with transparent backgrounds."""

    import os

    os.makedirs(outputdir, existok=True)

    for i in range(len(instances)):

    mask = instances.predmasks[i].cpu().numpy()

    box = instances.predboxes[i].tensor.cpu().numpy()[0].astype(int)

    x1, y1, x2, y2 = box

    crop = image[y1:y2, x1:x2].copy()

    maskcrop = mask[y1:y2, x1:x2]

    # Create RGBA image with transparency

    rgba = cv2.cvtColor(crop, cv2.COLORBGR2BGRA)

    rgba[:, :, 3] = (maskcrop 255).astype(np.uint8)

    cv2.imwrite(f"{outputdir}/object{i}.png", rgba)

    extractmaskedobjects(image, instances)


    Semantic Segmentation

    Semantic segmentation assigns a class label to every pixel in the image.

    # Semantic segmentation with DeepLabV3+
    

    cfg = getcfg()

    cfg.mergefromfile(modelzoo.getconfigfile(

    "Misc/semanticR50FPN1x.yaml"

    ))

    cfg.MODEL.WEIGHTS = modelzoo.getcheckpointurl(

    "Misc/semanticR50FPN1x.yaml"

    )

    cfg.MODEL.DEVICE = "cuda"

    predictor = DefaultPredictor(cfg)

    image = cv2.imread("scene.jpg")

    outputs = predictor(image)

    Semantic segmentation output

    semseg = outputs["semseg"] # Shape: (numclasses, H, W) tensor

    predictions = semseg.argmax(dim=0).cpu().numpy() # (H, W) class indices

    print(f"Segmentation map shape: {predictions.shape}")

    print(f"Unique classes: {np.unique(predictions)}")

    Visualize semantic segmentation

    v = Visualizer(image[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]))

    outputvis = v.drawsemseg(semseg.argmax(dim=0).to("cpu"))

    cv2.imwrite("semanticsegmentation.jpg", outputvis.getimage()[:, :, ::-1])

    Calculate class-wise pixel statistics

    def analyzesegmentation(predictions, metadata):

    """Analyze the semantic segmentation output."""

    classes = metadata.stuffclasses

    totalpixels = predictions.size

    stats = {}

    for clsid in np.unique(predictions):

    clsname = classes[clsid] if clsid < len(classes) else f"class{clsid}"

    pixelcount = (predictions == clsid).sum()

    percentage = (pixelcount / totalpixels) 100

    stats[clsname] = {

    "pixelcount": int(pixelcount),

    "percentage": float(f"{percentage:.2f}")

    }

    return stats

    stats = analyzesegmentation(

    predictions,

    MetadataCatalog.get(cfg.DATASETS.TRAIN[0])

    )

    for clsname, info in sorted(stats.items(), key=lambda x: -x[1]["percentage"]):

    print(f" {clsname}: {info['percentage']:.1f}% ({info['pixelcount']} pixels)")


    Panoptic Segmentation

    Panoptic segmentation unifies instance and semantic segmentation, providing a complete scene understanding.

    # Panoptic segmentation
    

    predictor, cfg = setuppredictor(

    "COCO-PanopticSegmentation/panopticfpnR503x.yaml",

    threshold=0.5

    )

    image = cv2.imread("complexscene.jpg")

    outputs, segmentinfo = predictor(image)["panopticseg"]

    outputs: (H, W) tensor with segment IDs

    segmentinfo: list of dicts with segment metadata

    print(f"Number of segments: {len(segmentinfo)}")

    for seg in segmentinfo:

    categoryid = seg["categoryid"]

    isthing = seg["isthing"] # True = countable object, False = stuff

    area = seg["area"]

    segtype = "thing" if isthing else "stuff"

    print(f" Segment {seg['id']}: category={categoryid}, "

    f"type={segtype}, area={area}")

    Visualize panoptic segmentation

    from detectron2.utils.visualizer import ColorMode

    v = Visualizer(

    image[:, :, ::-1],

    MetadataCatalog.get(cfg.DATASETS.TRAIN[0]),

    instancemode=ColorMode.IMAGEBW

    )

    outputvis = v.drawpanopticsegpredictions(

    outputs.to("cpu"), segmentinfo

    )

    cv2.imwrite("panopticresult.jpg", outputvis.getimage()[:, :, ::-1])


    Preparing Custom Datasets in COCO Format

    COCO format is the standard for Detectron2. Here is how to prepare and register your dataset.

    import json
    

    import os

    from pathlib import Path

    def createcocoannotation(

    imagedir,

    annotations,

    outputpath,

    categories

    ):

    """

    Create a COCO-format annotation file.

    Args:

    imagedir: Directory containing images

    annotations: List of dicts with keys: filename, bboxes, categoryids, masks

    outputpath: Path to save the JSON file

    categories: List of dicts with keys: id, name, supercategory

    """

    cocoformat = {

    "images": [],

    "annotations": [],

    "categories": categories,

    }

    annotationid = 1

    for imgid, ann in enumerate(annotations, start=1):

    # Read image dimensions

    imgpath = os.path.join(imagedir, ann["filename"])

    img = cv2.imread(imgpath)

    h, w = img.shape[:2]

    cocoformat["images"].append({

    "id": imgid,

    "filename": ann["filename"],

    "width": w,

    "height": h,

    })

    for bbox, catid in zip(ann["bboxes"], ann["categoryids"]):

    xmin, ymin, boxw, boxh = bbox # COCO format

    area = boxw boxh

    cocoann = {

    "id": annotationid,

    "imageid": imgid,

    "categoryid": catid,

    "bbox": [xmin, ymin, boxw, boxh],

    "area": area,

    "iscrowd": 0,

    }

    # Add segmentation mask if available (polygon format)

    if "masks" in ann:

    cocoann["segmentation"] = ann["masks"][

    ann["bboxes"].index(bbox)

    ]

    cocoformat["annotations"].append(cocoann)

    annotationid += 1

    with open(outputpath, "w") as f:

    json.dump(cocoformat, f, indent=2)

    print(f"Created COCO annotation: {outputpath}")

    print(f" Images: {len(cocoformat['images'])}")

    print(f" Annotations: {len(cocoformat['annotations'])}")

    print(f" Categories: {len(cocoformat['categories'])}")

    Define your categories

    categories = [

    {"id": 1, "name": "car", "supercategory": "vehicle"},

    {"id": 2, "name": "truck", "supercategory": "vehicle"},

    {"id": 3, "name": "person", "supercategory": "human"},

    ]

    Register the dataset with Detectron2

    from detectron2.data import DatasetCatalog, MetadataCatalog

    from detectron2.data.datasets import registercocoinstances

    registercocoinstances(

    "mydatasettrain",

    {},

    "/data/annotations/train.json",

    "/data/images/train"

    )

    registercocoinstances(

    "mydatasetval",

    {},

    "/data/annotations/val.json",

    "/data/images/val"

    )

    Verify registration

    datasetdicts = DatasetCatalog.get("mydatasettrain")

    print(f"Training samples: {len(datasetdicts)}")

    metadata = MetadataCatalog.get("mydatasettrain")

    print(f"Classes: {metadata.thingclasses}")


    Training on Custom Datasets

    import os
    

    from detectron2.engine import DefaultTrainer, HookBase

    from detectron2.config import getcfg

    from detectron2 import modelzoo

    from detectron2.evaluation import COCOEvaluator

    import torch

    class CustomTrainer(DefaultTrainer):

    """Custom trainer with validation evaluation."""

    @classmethod

    def buildevaluator(cls, cfg, datasetname):

    return COCOEvaluator(

    datasetname,

    outputdir=os.path.join(cfg.OUTPUTDIR, "eval"),

    )

    def setuptrainingconfig(

    numclasses,

    traindataset,

    valdataset,

    outputdir,

    baselr=0.001,

    maxiter=5000,

    batchsize=4,

    numworkers=4,

    ):

    """Configure training for a custom dataset."""

    cfg = getcfg()

    # Start from a pre-trained Mask R-CNN model

    cfg.mergefromfile(modelzoo.getconfigfile(

    "COCO-InstanceSegmentation/maskrcnnR50FPN3x.yaml"

    ))

    cfg.MODEL.WEIGHTS = modelzoo.getcheckpointurl(

    "COCO-InstanceSegmentation/maskrcnnR50FPN3x.yaml"

    )

    # Dataset

    cfg.DATASETS.TRAIN = (traindataset,)

    cfg.DATASETS.TEST = (valdataset,)

    cfg.DATALOADER.NUMWORKERS = numworkers

    # Solver (training parameters)

    cfg.SOLVER.IMSPERBATCH = batchsize

    cfg.SOLVER.BASELR = baselr

    cfg.SOLVER.MAXITER = maxiter

    cfg.SOLVER.STEPS = (int(maxiter 0.6), int(maxiter 0.8))

    cfg.SOLVER.GAMMA = 0.1

    cfg.SOLVER.WARMUPITERS = min(1000, maxiter // 10)

    cfg.SOLVER.WARMUPMETHOD = "linear"

    cfg.SOLVER.WEIGHTDECAY = 0.0001

    cfg.SOLVER.CHECKPOINTPERIOD = maxiter // 5

    # Model head

    cfg.MODEL.ROIHEADS.NUMCLASSES = numclasses

    cfg.MODEL.ROIHEADS.BATCHSIZEPERIMAGE = 128

    # Test

    cfg.TEST.EVALPERIOD = maxiter // 10

    # Output

    cfg.OUTPUTDIR = outputdir

    os.makedirs(cfg.OUTPUTDIR, existok=True)

    return cfg

    Configure and train

    cfg = setuptrainingconfig(

    numclasses=3,

    traindataset="mydatasettrain",

    valdataset="mydatasetval",

    outputdir="./output/custommodel",

    baselr=0.0025,

    maxiter=10000,

    batchsize=4,

    )

    Start training

    trainer = CustomTrainer(cfg)

    trainer.resumeorload(resume=False)

    trainer.train()

    Evaluate the trained model

    from detectron2.evaluation import inferenceondataset

    from detectron2.data import builddetectiontestloader

    evaluator = COCOEvaluator("mydatasetval", outputdir="./output/eval")

    valloader = builddetectiontestloader(cfg, "mydatasetval")

    results = inferenceondataset(trainer.model, valloader, evaluator)

    print(results)


    The Config System

    Detectron2's config system is powerful but can be complex. Here is a deep dive.

    from detectron2.config import getcfg, CfgNode
    
    

    Method 1: YAML-based configuration

    cfg = getcfg()

    cfg.mergefromfile("configs/myconfig.yaml")

    Method 2: Programmatic configuration

    cfg = getcfg()

    cfg.MODEL.BACKBONE.NAME = "buildresnetfpnbackbone"

    cfg.MODEL.RESNETS.DEPTH = 101

    cfg.MODEL.FPN.INFEATURES = ["res2", "res3", "res4", "res5"]

    Method 3: Override from command line arguments

    cfg.mergefromlist([

    "MODEL.WEIGHTS", "path/to/weights.pth",

    "SOLVER.BASELR", "0.001",

    "SOLVER.MAXITER", "5000",

    ])

    Method 4: Custom config keys

    cfg.MYCUSTOM = CfgNode()

    cfg.MYCUSTOM.SETTING1 = "value"

    cfg.MYCUSTOM.SETTING2 = 42

    Freeze config to prevent accidental changes during training

    cfg.freeze()

    Save and load configurations

    def saveconfig(cfg, outputpath):

    """Save configuration for reproducibility."""

    with open(outputpath, "w") as f:

    f.write(cfg.dump())

    print(f"Config saved to {outputpath}")

    def loadconfig(configpath, overrides=None):

    """Load a saved configuration."""

    cfg = getcfg()

    cfg.mergefromfile(configpath)

    if overrides:

    cfg.mergefromlist(overrides)

    return cfg

    Common configuration patterns

    def configureforsmalldataset(cfg, numimages):

    """Adjust config for small datasets to prevent overfitting."""

    cfg.SOLVER.IMSPERBATCH = 2

    cfg.SOLVER.BASELR = 0.0005

    cfg.SOLVER.MAXITER = numimages 50 # ~50 epochs

    cfg.SOLVER.WARMUPITERS = min(500, cfg.SOLVER.MAXITER // 10)

    cfg.MODEL.ROIHEADS.BATCHSIZEPERIMAGE = 64

    # Add augmentations for small datasets

    cfg.INPUT.MINSIZETRAIN = (480, 512, 544, 576, 608, 640)

    cfg.INPUT.MAXSIZETRAIN = 800

    cfg.INPUT.RANDOMFLIP = "horizontal"

    return cfg


    Model Zoo

    Detectron2's Model Zoo provides pre-trained models across multiple tasks.

    from detectron2 import modelzoo
    
    

    List available models

    Detection models

    detectionmodels = [

    "COCO-Detection/fasterrcnnR50FPN3x.yaml",

    "COCO-Detection/fasterrcnnR101FPN3x.yaml",

    "COCO-Detection/fasterrcnnX10132x8dFPN3x.yaml",

    "COCO-Detection/retinanetR50FPN3x.yaml",

    ]

    Instance segmentation models

    instancemodels = [

    "COCO-InstanceSegmentation/maskrcnnR50FPN3x.yaml",

    "COCO-InstanceSegmentation/maskrcnnR101FPN3x.yaml",

    "COCO-InstanceSegmentation/maskrcnnX10132x8dFPN3x.yaml",

    ]

    Panoptic segmentation

    panopticmodels = [

    "COCO-PanopticSegmentation/panopticfpnR503x.yaml",

    "COCO-PanopticSegmentation/panopticfpnR1013x.yaml",

    ]

    Keypoint detection

    keypointmodels = [

    "COCO-Keypoints/keypointrcnnR50FPN3x.yaml",

    "COCO-Keypoints/keypointrcnnR101FPN3x.yaml",

    ]

    def comparemodels(image, modelconfigs, threshold=0.5):

    """Compare predictions from multiple models."""

    results = {}

    for configpath in modelconfigs:

    modelname = configpath.split("/")[-1].replace(".yaml", "")

    cfg = getcfg()

    cfg.mergefromfile(modelzoo.getconfigfile(configpath))

    cfg.MODEL.WEIGHTS = modelzoo.getcheckpointurl(configpath)

    cfg.MODEL.ROIHEADS.SCORETHRESHTEST = threshold

    predictor = DefaultPredictor(cfg)

    import time

    start = time.time()

    outputs = predictor(image)

    inferencetime = time.time() - start

    numdetections = len(outputs["instances"])

    results[modelname] = {

    "detections": numdetections,

    "inferencetimems": inferencetime 1000,

    }

    print(f"{modelname}: {numdetections} detections in "

    f"{inferencetime1000:.1f}ms")

    return results


    Evaluation Metrics

    Understanding evaluation metrics is critical for measuring model quality.

    from detectron2.evaluation import COCOEvaluator, inferenceondataset
    

    from detectron2.data import builddetectiontestloader

    def comprehensiveevaluation(cfg, model, datasetname):

    """Run comprehensive evaluation with detailed metrics."""

    evaluator = COCOEvaluator(

    datasetname,

    tasks=("bbox", "segm"), # Evaluate both box and mask

    outputdir=os.path.join(cfg.OUTPUTDIR, "eval"),

    )

    valloader = builddetectiontestloader(cfg, datasetname)

    results = inferenceondataset(model, valloader, evaluator)

    # Parse COCO metrics

    if "bbox" in results:

    bboxresults = results["bbox"]

    print("\nBounding Box Metrics:")

    print(f" AP (IoU=0.50:0.95): {bboxresults['AP']:.3f}")

    print(f" AP50 (IoU=0.50): {bboxresults['AP50']:.3f}")

    print(f" AP75 (IoU=0.75): {bboxresults['AP75']:.3f}")

    print(f" AP-small: {bboxresults['APs']:.3f}")

    print(f" AP-medium: {bboxresults['APm']:.3f}")

    print(f" AP-large: {bboxresults['APl']:.3f}")

    if "segm" in results:

    segmresults = results["segm"]

    print("\nSegmentation Metrics:")

    print(f" AP (IoU=0.50:0.95): {segmresults['AP']:.3f}")

    print(f" AP50 (IoU=0.50): {segmresults['AP50']:.3f}")

    print(f" AP75 (IoU=0.75): {segmresults['AP75']:.3f}")

    return results

    Per-class evaluation

    def perclassevaluation(cfg, model, datasetname):

    """Evaluate per-class performance."""

    evaluator = COCOEvaluator(datasetname, outputdir="./evaloutput")

    valloader = builddetectiontestloader(cfg, datasetname)

    results = inferenceondataset(model, valloader, evaluator)

    # Access per-class AP from COCO evaluator

    cocoeval = evaluator.cocoeval

    if cocoeval and "bbox" in cocoeval:

    precisions = cocoeval["bbox"].eval["precision"]

    # precisions shape: [T, R, K, A, M]

    # T: IoU thresholds, R: recall thresholds, K: categories

    # A: area ranges, M: max detections

    metadata = MetadataCatalog.get(datasetname)

    classnames = metadata.thingclasses

    print("\nPer-class AP50:")

    for idx, clsname in enumerate(classnames):

    # AP50 = precision at IoU=0.5 (index 0), all recall, area=all, maxDet=100

    precision = precisions[0, :, idx, 0, -1]

    precision = precision[precision > -1]

    ap = np.mean(precision) if len(precision) > 0 else 0

    print(f" {clsname}: {ap:.3f}")

    return results


    Deployment

    Deploy Detectron2 models for production inference.

    import torch
    

    from detectron2.export import TracingAdapter

    from detectron2.modeling import buildmodel

    from detectron2.checkpoint import DetectionCheckpointer

    Method 1: TorchScript Export

    def exporttorchscript(cfg, outputpath):

    """Export model to TorchScript for deployment."""

    cfg = cfg.clone()

    cfg.MODEL.DEVICE = "cpu"

    model = buildmodel(cfg)

    DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS)

    model.eval()

    # Create sample input

    sampleinput = torch.randn(1, 3, 800, 800)

    # Trace the model

    traced = torch.jit.trace(model, sampleinput)

    torch.jit.save(traced, outputpath)

    print(f"TorchScript model saved to {outputpath}")

    Method 2: ONNX Export

    def exportonnx(cfg, outputpath):

    """Export model to ONNX format."""

    cfg = cfg.clone()

    cfg.MODEL.DEVICE = "cpu"

    model = buildmodel(cfg)

    DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS)

    model.eval()

    sampleinput = torch.randn(1, 3, 800, 800)

    torch.onnx.export(

    model,

    sampleinput,

    outputpath,

    opsetversion=11,

    inputnames=["input"],

    outputnames=["boxes", "scores", "classes"],

    dynamicaxes={

    "input": {0: "batchsize", 2: "height", 3: "width"},

    },

    )

    print(f"ONNX model saved to {outputpath}")

    Method 3: Optimized Inference Server

    class DetectionServer:

    """Production-ready detection server."""

    def init(self, configpath, weightspath, threshold=0.5, device="cuda"):

    self.cfg = getcfg()

    self.cfg.mergefromfile(configpath)

    self.cfg.MODEL.WEIGHTS = weightspath

    self.cfg.MODEL.ROIHEADS.SCORETHRESHTEST = threshold

    self.cfg.MODEL.DEVICE = device

    self.predictor = DefaultPredictor(self.cfg)

    self.metadata = MetadataCatalog.get(self.cfg.DATASETS.TRAIN[0])

    # Warmup

    dummy = np.zeros((640, 640, 3), dtype=np.uint8)

    self.predictor(dummy)

    def predict(self, image):

    """Run detection on an image."""

    outputs = self.predictor(image)

    instances = outputs["instances"].to("cpu")

    results = []

    for i in range(len(instances)):

    box = instances.predboxes[i].tensor.numpy()[0]

    result = {

    "class": self.metadata.thingclasses[instances.predclasses[i]],

    "confidence": float(instances.scores[i]),

    "bbox": {

    "x1": float(box[0]),

    "y1": float(box[1]),

    "x2": float(box[2]),

    "y2": float(box[3]),

    },

    }

    if instances.has("predmasks"):

    result["mask"] = instances.predmasks[i].numpy().tolist()

    results.append(result)

    return results

    def predictbatch(self, images):

    """Run detection on a batch of images."""

    return [self.predict(img) for img in images]

    Usage

    server = DetectionServer(

    configpath="./output/custommodel/config.yaml",

    weightspath="./output/custommodel/modelfinal.pth",

    threshold=0.5,

    )

    image = cv2.imread("test.jpg")

    detections = server.predict(image)

    for det in detections:

    print(f" {det['class']}: {det['confidence']:.3f} at {det['bbox']}")


    Best Practices

    1. Choosing the Right Model

    # Speed vs accuracy trade-offs:
    

    Fast inference: RetinaNet R-50 FPN (~15 FPS on V100)

    Balanced: Faster R-CNN R-50 FPN (~12 FPS on V100)

    High accuracy: Mask R-CNN X-101-FPN (~5 FPS on V100)

    Best accuracy: Cascade Mask R-CNN X-101 (~3 FPS on V100)

    2. Data Augmentation for Detection

    # Configure input augmentation in config
    

    cfg.INPUT.MINSIZETRAIN = (640, 672, 704, 736, 768, 800)

    cfg.INPUT.MAXSIZETRAIN = 1333

    cfg.INPUT.MINSIZETEST = 800

    cfg.INPUT.MAXSIZETEST = 1333

    cfg.INPUT.RANDOMFLIP = "horizontal"

    3. Learning Rate Scheduling

    # Use warmup + step decay for stable training
    

    cfg.SOLVER.WARMUPITERS = 1000

    cfg.SOLVER.WARMUPMETHOD = "linear"

    cfg.SOLVER.WARMUPFACTOR = 1.0 / 1000

    Step decay at 60% and 80% of total iterations

    totaliters = 10000

    cfg.SOLVER.STEPS = (int(totaliters 0.6), int(totaliters 0.8))

    cfg.SOLVER.GAMMA = 0.1

    4. Monitor Training with TensorBoard

    # Detectron2 logs to TensorBoard by default
    

    Launch TensorBoard:

    tensorboard --logdir ./output/custommodel

    Key metrics to monitor:

    - totalloss: Overall training loss

    - losscls: Classification loss

    - lossboxreg: Bounding box regression loss

    - lossmask: Mask prediction loss (if using Mask R-CNN)

    - lr: Learning rate schedule

    5. Handle Class Imbalance

    # For imbalanced datasets, adjust the sampler
    

    cfg.DATALOADER.SAMPLERTRAIN = "RepeatFactorTrainingSampler"

    cfg.DATALOADER.REPEATTHRESHOLD = 0.001 # Repeat images with rare classes


    Conclusion

    Detectron2 is a comprehensive and production-ready framework for object detection and segmentation. In this tutorial, you learned:

    • How to set up Detectron2 and use pre-trained models for immediate inference
    • The differences between instance, semantic, and panoptic segmentation
    • How to prepare custom datasets in COCO format and register them
    • Training workflows with custom configs and evaluation
    • The config system's flexibility for controlling every aspect of the model
    • Navigating Model Zoo for the right speed-accuracy trade-off
    • Understanding COCO evaluation metrics (AP, AP50, AP75, etc.)
    • Deploying models via TorchScript, ONNX, or custom inference servers

    Detectron2 powers many production systems at Facebook/Meta and in the broader computer vision community. Its modular design makes it an excellent foundation for both research experimentation and production deployment.

    For more information, visit the official documentation at detectron2.readthedocs.io.

    Related Articles

    Florence-2: Microsoft's Multi-Task Vision Foundation Model

    Florence-2: Model Vision Multi-Task dari Microsoft Daftar Isi Pendahuluan Prasyarat Instalasi Memuat Model Florence-2

    Supervision: Computer Vision Toolkit by Roboflow

    Supervision: Toolkit Computer Vision dari Roboflow Dalam proyek computer vision, setelah model mendeteksi objek, Anda ma...

    Complete Ultralytics Tutorial: Object Detection with YOLO

    Tutorial Lengkap Ultralytics: Object Detection dengan YOLO Ultralytics adalah framework Python yang menyediakan implemen...

    Complete Guide to DETR: Object Detection with Transformers

    Panduan Lengkap DETR: Object Detection dengan Transformers DETR (DEtection TRansformer) adalah pendekatan revolusioner u...