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
.ipynbnotebooks 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-runand 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 |
|---|---|---|
Video metadata, |
||
Occlusion gap filling, IQR outlier filtering, path length, speed, pairwise distances, |
||
Arena midline swap repair, static landmark mode fill, rolling-window gap repair, and |
||
COCO RLE mask decoding, area/perimeter filtering, IoU-based overlap merging, and batch CSV folder cleanup |
||
Frame-to-timestamp conversion, smoothed |
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
4. Video Embeddings & Natural-Language Behavior Search#
The legacy Annolid_Video_Embeddings.ipynb notebook extracted backbone box-predictor in_features from a trained Detectron2 model to inspect clusters in TensorBoard Projector. Today, Annolid ships native, zero-PyTorch semantic frame search powered by ONNX EmbeddingGemma 2:
# Search hours of video using plain-English behavioral queries
annolid-run behavior-search /path/to/trial.mp4 \
--query "mouse rearing near wall" \
--stride 5 \
--index-cache ./trial_eg2.npz \
--json
See Frame Search & Identity Repair for GUI and Python usage.
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:
Mask-scoped Farnebäck optical flow & freezing bouts: see Freezing & Dense Motion Assays.
Polygon/pose Temporal Convolutional Network (TCN) classifiers & 1-second VLM ethogram labeling: see Behavior Scoring & Ethograms and TCN Behavior Classification.
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)
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 ( |
Classification |
Current Destination |
|---|---|---|
|
Runnable Book Notebook |
|
|
Runnable Book Notebook |
|
|
Runnable Book Notebook |
|
|
Runnable Book Notebook |
|
|
Runnable Book Notebook (consolidated) |
|
|
Runnable Book Notebook |
|
|
Active Colab GPU Notebook |
|
|
Active Colab GPU Notebook |
|
|
Active Colab GPU Notebook |
|
|
Active Colab GPU Notebook / Example |
Recipe 1 above · Open in Colab |
|
Example Code Recipe (Cloud/Legacy) |
Recipe 2 above · Power-User CLI |
|
Example Code Recipe (Cluster) |
Recipe 2 above |
|
Example Code Recipe (FiftyOne) |
Recipe 3 above · Track QC & Reports |
|
Example Code Recipe / Superseded |
Recipe 4 above · Frame Search & Identity Repair |
|
Example Code Recipe / Superseded |
Recipe 5 above · Freezing & Dense Motion Assays |
|
Example Code Recipe / Research |
Recipe 5 above · Freezing & Dense Motion Assays |
|
Example Code Recipe / Superseded |
Recipe 5 above · TCN Behavior Classification |
|
Example Code Recipe / Integrated |
Recipe 6 above · Labeling Instances & SAM3 |
|
Example Code Recipe / Integrated |
Recipe 6 above · Labeling Instances |
|
Example Code Recipe / Integrated |
Recipe 6 above · Model Training |
|
Example Code Recipe (External) |
Recipe 6 above · Realtime & Multi-Camera |
|
Legacy Colab / Example Code |
Recipe 6 above · Google Colab Guide |
|
Legacy Example Code |
Recipe 6 above · Model Training |
|
Legacy Example Code (YOLACT) |
Recipe 6 above · Model Training |