Example Code Recipes & Notebook Migration Guide#

Not every research workflow belongs in a locally executed Jupyter notebook: some tutorials run cleanly on a laptop CPU with synthetic or local data, while others require cloud GPUs (Google Colab), third-party cluster stacks (Ray, FiftyOne, SAHI), or legacy frameworks (Detectron2, YOLACT, SlowFast).

To keep The Annolid Book reliable and reproducible:

  • Runnable local tutorials live as verified, self-contained .ipynb notebooks in the Interactive Jupyter Notebooks part of this book (every cell runs offline on synthetic demo data out of the box, or on your own video/CSV by changing a single path variable).

  • Cloud-GPU notebooks remain directly launchable via one-click Open in Colab badges on Running Annolid on Google Colab.

  • Non-runnable / external-framework / legacy examples are distilled into copy-pasteable example code recipes right here, alongside their modern annolid-run and Python equivalents.

Runnable Jupyter Book Notebooks#

Open or download any of the five locally runnable notebooks included in this book:

Notebook

What It Covers

Companion Guide

Extract Frames from a Video

Video metadata, uniform / kmeans smart frame sampling, explicit frame indices, and batch folders

Extracting Frames

Inter-Instance Distances & Kinematics

Occlusion gap filling, IQR outlier filtering, path length, speed, pairwise distances, TrackingResultsAnalyzer, and analyze_kinematics

Inter-Instance Distances

Fix Left/Right Label Switches & Gaps

Arena midline swap repair, static landmark mode fill, rolling-window gap repair, and evaluate_track_qc audit

Track QC & Reports

Mask Areas, Perimeters, IoU Merging & Batch Folders

COCO RLE mask decoding, area/perimeter filtering, IoU-based overlap merging, and batch CSV folder cleanup

COCO & Data Formats

Digging Bout & ROI Overlap Analysis

Frame-to-timestamp conversion, smoothed rat–cup mask IoU bout detection, bout onset merging, and CSV export

Behavior Scoring & Ethograms


Example Code Recipes (Non-Runnable / External / Cloud Workflows)#

The snippets below preserve the useful code patterns from historical docs/tutorials/*.ipynb notebooks that depend on private datasets, cloud GPUs, or third-party external libraries, paired with Annolid’s current built-in workflows.

1. Cloud GPU Training & Sliced Inference (YOLO & SAHI)#

For training YOLO11 / YOLO26 / YOLOE segmentation or pose models on cloud GPUs, prefer Google Colab Studio (annolid-run colab) or launch the official Colab notebooks directly. When detecting very small animals in wide high-resolution frames, combine Ultralytics weights with SAHI (Sliced Aided Hyper Inference):

# Example pattern (requires: pip install sahi ultralytics torch)
from sahi import AutoDetectionModel
from sahi.predict import get_sliced_prediction

detection_model = AutoDetectionModel.from_pretrained(
    model_type="yolov8",
    model_path="/path/to/best.pt",
    confidence_threshold=0.3,
    device="cuda:0",  # or "cpu"
)

result = get_sliced_prediction(
    "/path/to/wide_arena_frame.png",
    detection_model,
    slice_height=512,
    slice_width=512,
    overlap_height_ratio=0.2,
    overlap_width_ratio=0.2,
)
print(f"Detected {len(result.object_prediction_list)} objects across slices.")

Modern built-in Annolid equivalent for training and inference:

# Train locally or dispatch to a Colab T4/L4/A100 GPU
annolid-run colab train yolo --data ./YOLO_dataset/data.yaml --weights yolo11s-seg.pt --gpu T4
annolid-run predict yolo_labelme --source /path/to/video.mp4 --weights /path/to/best.pt

2. Batch Video Inference & Distributed Worker Serving#

Historical notebooks (Annolid_video_batch_inference.ipynb and Annolid_inference_ray_cluster.ipynb) demonstrated batch processing videos with annolid.inference.predict.Segmentor and serving frames over HTTP with Ray Serve. Modern Annolid projects can batch-process videos directly via annolid-run or wrap Segmentor inside a lightweight worker loop:

# Modern batch CLI pattern (recommended — works with YOLO, Cutie, SAM3, pose models)
import subprocess
from pathlib import Path

for video in sorted(Path("/path/to/videos").glob("*.mp4")):
    subprocess.run(
        [
            "annolid-run",
            "predict",
            "yolo_labelme",
            "--source",
            str(video),
            "--weights",
            "/path/to/best.pt",
        ],
        check=True,
    )

Conceptual HTTP worker pattern (adapted from the legacy Ray Serve cluster example; requires ray[serve] + trained Detectron2 weights):

# Example only — requires a trained Detectron2 checkpoint and Ray Serve 2.x
import cv2
import numpy as np
from ray import serve
from annolid.inference.predict import Segmentor


@serve.deployment(num_replicas=2)
class AnnolidFrameWorker:
    def __init__(self, dataset_dir: str, model_path: str):
        self.model = Segmentor(dataset_dir, model_path)

    async def __call__(self, request):
        payload = await request.body()
        buf = np.frombuffer(payload, dtype=np.uint8)
        frame = cv2.imdecode(buf, cv2.IMREAD_COLOR)
        return self.model.on_image(frame)

3. Model Evaluation (FiftyOne & Built-In Pose Evaluation)#

To visually inspect COCO ground-truth vs. predicted masks in FiftyOne (adapted from Annolid_model_evaluation.ipynb, requires pip install fiftyone and a COCO dataset + trained model):

# Example only — requires fiftyone + COCO validation dataset
import fiftyone

dataset = fiftyone.Dataset.from_dir(
    dataset_type=fiftyone.types.COCODetectionDataset,
    data_path="/path/to/my_coco_dataset/valid",
    labels_path="/path/to/my_coco_dataset/valid/annotations.json",
    label_types="segmentations",
)
# After attaching predictions to each sample under sample["predictions"]:
eval_results = dataset.evaluate_detections(
    "predictions",
    gt_field="ground_truth",
    eval_key="eval",
    compute_mAP=True,
)
eval_results.print_report()

Modern built-in Annolid alternatives (no external FiftyOne server required):

# Pose keypoint evaluation (PCK, OKS, RMSE, per-keypoint error tables)
annolid-run eval-pose ./gt_labelme ./pred_labelme --pose-schema ./pose_schema.json --output-dir ./pose_eval

# Track QC & prioritized manual review queue
annolid-run track-qc session_tracked.csv --expected-instances 2 --fps 30 --review-csv review_queue.csv

5. Optical Flow & Supervised Video Behavior Classification#

Historical research notebooks explored external optical-flow repos (RAFT, self-supervised optical flow) and SlowFast video clip classifiers (pytorchvideo / fvcore):

# Example pattern (adapted from SlowFast tutorial; requires pytorchvideo + fvcore + pyav)
import torch

model = torch.hub.load("facebookresearch/pytorchvideo", "slowfast_r50", pretrained=True)
model = model.eval().to("cuda" if torch.cuda.is_available() else "cpu")

For day-to-day lab work, Annolid now builds these capabilities directly into the main package:

6. Zero-Shot Masking Prototypes & Legacy Detectron2 / YOLACT Reference#

Earlier prototype notebooks (zero_shot_object_detection_and_tracking_with_grounding_dino.ipynb, automatic_mask_generator_example.ipynb, yolov8_tracking_tutorial.ipynb, Follow_Anything.ipynb) cloned external repositories in Colab. Today, Annolid integrates SAM AI-Polygons, Grounding DINO → SAM text prompts, SAM3, Cutie, INSID3, and YOLO11/YOLO26 natively inside the desktop GUI and annolid-run.

For labs maintaining legacy Detectron2 Mask R-CNN or PointRend datasets (Annolid_on_Detectron2_Tutorial.ipynb, PointRend_in_Detectron2_Tutorial.ipynb), the core dataset-registration pattern is:

# Example only — requires detectron2 installed in a compatible CUDA/PyTorch environment
from detectron2.config import get_cfg
from detectron2.data.datasets import register_coco_instances
from detectron2.engine import DefaultPredictor
from detectron2 import model_zoo

register_coco_instances("annolid_train", {}, "/path/to/train/annotations.json", "/path/to/train")
register_coco_instances("annolid_val", {}, "/path/to/valid/annotations.json", "/path/to/valid")

cfg = get_cfg()
cfg.merge_from_file(
    model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
)
cfg.MODEL.WEIGHTS = "/path/to/model_final.pth"
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 2
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
predictor = DefaultPredictor(cfg)

Tip

Migrating off Detectron2 or YOLACT (Train_networks_tutorial_v1.0.1.ipynb)? Export your LabelMe or COCO annotations directly to YOLO format via File → Convert Labelme to YOLO format (or annolid-run index-to-yolo), or track directly from a single seed frame with Cutie or SAM3.


Complete Migration Index (docs/tutorials/*.ipynb)#

Every historical notebook in docs/tutorials/ is preserved at its original GitHub path for backward compatibility with external links and Colab badges, and mapped to its current home below:

Source Notebook (docs/tutorials/)

Classification

Current Destination

Extract_frames_from_a_video.ipynb

Runnable Book Notebook

Extract Frames from a Video

Annolid_post_processing_distances.ipynb

Runnable Book Notebook

Inter-Instance Distances & Kinematics

Annolid_post_processing_fix_left_right_switch.ipynb

Runnable Book Notebook

Fix Left/Right Label Switches & Gaps

Annolid_post_processinng_masks_ious_and_areas.ipynb

Runnable Book Notebook

Mask Areas, Perimeters, IoU Merging & Batch Folders

Annolid_batch_post_processinng_tracking_csv_for_masks_ious_and_areas.ipynb

Runnable Book Notebook (consolidated)

Mask Areas, Perimeters, IoU Merging & Batch Folders

Digging_Analysis_tutorial.ipynb

Runnable Book Notebook

Digging Bout & ROI Overlap Analysis

Annolid_Colab_Train_and_Inference.ipynb

Active Colab GPU Notebook

Google Colab Guide · Open in Colab

Annolid_Instance_Segmentation_on_YOLO_Tutorial.ipynb

Active Colab GPU Notebook

Google Colab Guide · Open in Colab

Annolid_Pose_Estimation_on_YOLO_Tutorial.ipynb

Active Colab GPU Notebook

Google Colab Guide · Open in Colab

YOLO_SAHI_inference_for_ultralytics.ipynb

Active Colab GPU Notebook / Example

Recipe 1 above · Open in Colab

Annolid_video_batch_inference.ipynb

Example Code Recipe (Cloud/Legacy)

Recipe 2 above · Power-User CLI

Annolid_inference_ray_cluster.ipynb

Example Code Recipe (Cluster)

Recipe 2 above

Annolid_model_evaluation.ipynb

Example Code Recipe (FiftyOne)

Recipe 3 above · Track QC & Reports

Annolid_Video_Embeddings.ipynb

Example Code Recipe / Superseded

Recipe 4 above · Frame Search & Identity Repair

RAFT_optical_flow.ipynb

Example Code Recipe / Superseded

Recipe 5 above · Freezing & Dense Motion Assays

Self_supervised_optical_flow_estimation.ipynb

Example Code Recipe / Research

Recipe 5 above · Freezing & Dense Motion Assays

Annolid_behavior_video_classification_on_slowfast.ipynb

Example Code Recipe / Superseded

Recipe 5 above · TCN Behavior Classification

zero_shot_object_detection_and_tracking_with_grounding_dino.ipynb

Example Code Recipe / Integrated

Recipe 6 above · Labeling Instances & SAM3

automatic_mask_generator_example.ipynb

Example Code Recipe / Integrated

Recipe 6 above · Labeling Instances

yolov8_tracking_tutorial.ipynb

Example Code Recipe / Integrated

Recipe 6 above · Model Training

Follow_Anything.ipynb

Example Code Recipe (External)

Recipe 6 above · Realtime & Multi-Camera

Annolid_on_Detectron2_Tutorial.ipynb

Legacy Colab / Example Code

Recipe 6 above · Google Colab Guide

PointRend_in_Detectron2_Tutorial.ipynb

Legacy Example Code

Recipe 6 above · Model Training

Train_networks_tutorial_v1.0.1.ipynb

Legacy Example Code (YOLACT)

Recipe 6 above · Model Training