Skip to content

Latest commit

 

History

History

tools

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

CLI script implementations

After uv pip install -e . (or make install), use the odet command for day-to-day work (odet train, odet preds, …). See oriented_det/cli/README.md and the repository map in the main README.

Common commands

Install once: uv pip install -e .. Then:

Task Command
Train odet train --config configs/oriented_rcnn/dota_le90_1x.json or make train
Multi-GPU make train-multi-gpu (torchrun + cuDNN on LD_LIBRARY_PATH)
Tile DOTA odet tile-dota /path/to/data/DOTA-v1.0/train
HRSC2016 → DOTA (optional) odet hrsc-to-dota --data-root /path/to/data/HRSC2016 --output-dir /path/to/data/HRSC2016-dota
SSDD → DOTA (optional) odet ssdd-to-dota --data-root /path/to/data/Official-SSDD-OPEN --output-dir /path/to/data/SSDD-dota
COCO polygons → DOTA odet coco-to-dota --ann-file instances.json --image-dir images --output-dir out
Val predictions odet preds --experiment-dir runs/oriented_rcnn/<timestamp> or make preds
Offline mAP make eval-val or make preds then make metrics. DOTA: leaky val tiles (real test is Task 1). HRSC/FAIR1M/SSDD/HRSID: held-out test/val.
ONNX export odet export onnx ... or make export-onnx (see export/README.md)

DOTA configs: per-model dota_le90_1x.json under configs/ (3× where published; Faster R-CNN and FCOS DOTA are 1×). Run odet --help for all subcommands. Config reference: docs/user-guide/configuration.md, configs/config.schema.json, configs/README.md.

This directory holds the Python modules that implement odet subcommands and supports direct python tools/... invocation. Shared inference and collate logic lives in oriented_det/runtime/.

PyPI configs: sync_vendored_configs.py copies manifest-listed files from repo configs/ → oriented_det/configs/. Use make sync-configs / make check-configs (see configs/README.md).

Running without odet: From the repo root, python tools/train.py --config … is equivalent to odet train --config … for debugging. Prefer odet or make in docs and CI so paths stay consistent.

Thin compatibility modules: tools/inference.py and tools/helpers.py re-export oriented_det.runtime and emit a deprecation warning; new code should import from oriented_det.runtime.inference and oriented_det.runtime.collate directly.

ONNX export is not in tools/. Use odet export / make export-onnx (export/README.md, docs/examples/export.md).

Quick Start with Makefile

From the repository root, the Makefile calls odet under the hood. Run make help for targets; defaults (CONFIG, DOTA paths) are at the top of the Makefile. Use make train-multi-gpu (not a raw odet train in a misconfigured shell) so torchrun -m oriented_det.cli.train and pip cuDNN on LD_LIBRARY_PATH are applied.

Common targets:

make install          # Install the package (required before running tools)
make help             # Show all available commands
make train            # Train with CONFIG (checkpoint.* in JSON only)
make train-multi-gpu  # Multi-GPU training (same CONFIG)
make eval-val           # `make preds` then `make metrics` on newest `predictions/<ts>/` (DOTA val is leaky; real test is Task 1)
make eval-test          # same pipeline on the configured labeled test split (refuses recipes with none)
make preds              # Val inference → `predictions/<ts>/` (experiment `production.*`; no GPU mAP)
make metrics            # Offline mAP/PR from latest `predictions/*/` or `METRICS_PRED_DIR=...` (defaults from JSON metadata)
make dota-submit        # Task 1 zip: FROM_JSON=, CHECKPOINT=hf://<slug>, or EXPERIMENT= + TEST_DIR= (OUT= required)
make dota-submit        # Task 1 zip: FROM_JSON=, CHECKPOINT=hf://<slug>, or EXPERIMENT= + TEST_DIR= (OUT= required)
make viewer             # Gradio: browse latest tiled predictions under `predictions/` (run `make preds` first)
make demo               # image_demo on all top-level images in demo/ (latest exp; see demo/README.md)
make free-gpu         # Kill GPU processes to free memory
make test             # Run tests
make docs-serve       # Build and serve documentation
make clean            # Remove generated output files

For tiling and inference on single images, run the scripts directly (see Scripts below); there are no make tile / make inference targets.

Scripts

image_demo.py

Run inference on image(s) using oriented-det config + checkpoint. Loads model type, num_classes, preprocessing, and class names from the config. For registered pretrained weights, you can omit the config and pass only hf://<slug>; the checkpoint sidecar JSON is used automatically. If you do pass a config, a sidecar config beside the .pth is preferred only when the provided config is the checkpoint's manifest source_recipe; a different config is kept as-is. Detection labels are 1-based foreground ids (same convention as training class_map); overlay text uses class_names[label - 1].

Inference: Same as run_inference_auto: pad always one training-style whole-image forward; fixed/crop one forward when the image fits the canvas, otherwise run_inference_sliding_window. Use --zoom 2 or --zoom 4 to upscale for inference only; detections are mapped back to the original image before visualization.

Usage:

# Single image (output path optional)
python tools/image_demo.py demo/demo.jpg configs/oriented_rcnn/dota_le90_1x.json runs/.../checkpoints/best.pth --out-file result.jpg

# Registered pretrained weights (sidecar config auto-resolved)
python tools/image_demo.py demo/demo.jpg hf://oriented_rcnn_dota_le90_3x --out-file result.jpg

# All images in a directory (writes to demo/out by default)
python tools/image_demo.py demo configs/.../config.json runs/.../checkpoints/best.pth --out-dir demo/out

# Options
python tools/image_demo.py demo/demo.jpg config.json checkpoint.pth \
    --out-file result.jpg --device cuda:0 --score-thr 0.3 --nms-thr 0.5 \
    --classes ship --zoom 2 --overlap-pixels 200 --ignore-margin-pixels 100 \
    --window-batch-size 8 --json-per-image --json-batch demo/out/json

Arguments: img (file or directory), then either checkpoint alone (registered pretrained checkpoint with sidecar config) or config + checkpoint. Optional: --out-file, --out-dir, --device, --score-thr, --nms-thr, --classes, --zoom, --overlap-pixels (default from production.overlap_pixels, else 200), --ignore-margin-pixels (default 0, keep overlap copies then NMS; else production.ignore_margin_pixels), --overlap-ratio (pad/tile path only; ratio overrides pixels), --window-batch-size (windows per forward; default 8 on GPU), --json-per-image (rich JSON next to each visualization: rbox, polygon, run metadata), or --json-batch [PATH] (compact batch JSON for pipelines: per-image files plus combined detections.json when img is a directory).

Demo images: place test images in demo/ (see demo/README.md for a sample image or using your own).

Makefile: make demo runs tools/image_demo.py on every top-level *.jpg / *.jpeg / *.png in DEMO_DIR (default demo/) with the latest runs/ checkpoint and config; outputs default to demo/out/. Variables: DEMO_DIR, IMAGE_DEMO_OUT_DIR, IMAGE_DEMO_DEVICE (see top-level Makefile).

Horizontal BB → oriented BB (hbb_to_obb.py, filter_predictions_by_gt.py, generate_oriented_annotations.py)

Convert horizontal ground-truth boxes to oriented boxes using model predictions from odet image-demo --json-batch:

  1. Run inference on images (high recall: e.g. --score-thr 0.05 --nms-thr 0.5).
  2. Match predictions to horizontal GT by oriented IoU; drop unmatched detections (false positives).
  3. For each GT box: use the matched oriented prediction, or fall back to the horizontal box (0°).

Supported GT formats (--gt-format):

Format Layout Notes
csv annotations.csv with id, image_id, geometry, class Polygon corners (axis-aligned OK)
yolo images/ + labels/*.txt class cx cy w h normalized
dota images/ + labelTxt/*.txt Standard DOTA lines

Output (--output-format): csv → annotations_oriented.csv; dota → per-image .txt in labels_oriented/.

# 1) Inference
odet image-demo /path/to/images hf://oriented_rcnn_dota_le90_3x \
  --classes plane --score-thr 0.05 --nms-thr 0.5 \
  --json-batch /path/to/predictions --out-dir /path/to/predictions/vis

# 2) Optional: filter only (inspect FP removal)
python tools/filter_predictions_by_gt.py \
  --gt-format csv --dataset-root /path/to/data --annotations annotations.csv \
  --detections-json /path/to/predictions/detections.json \
  --output-json /path/to/predictions/detections_gt_filtered.json \
  --ignore-class Truncated_airplane

# 3) Generate oriented annotations (CSV or DOTA)
python tools/generate_oriented_annotations.py \
  --gt-format yolo --dataset-root /path/to/data \
  --yolo-class-name 0=plane \
  --detections-json /path/to/predictions/detections.json \
  --output-format csv

# Compare raw prediction counts vs horizontal GT
python tools/compare_hbb_obb_counts.py \
  --gt-format csv --annotations annotations.csv \
  --detections-json /path/to/predictions/detections.json

Shared library: tools/hbb_to_obb.py.

train.py

Complete training script for oriented object detection models. Uses JSON configuration files (similar to MMRotate) and supports multiple model types.

TensorBoard: validation images under val/predictions include the source file basename (with extension) in a label at the top-left, taken from the collate target image_filename (oriented_det.runtime.collate).

Usage:

# Basic training with config file
python tools/train.py --config configs/oriented_rcnn/dota_le90_1x.json

# Override batch size
python tools/train.py --config configs/oriented_rcnn/dota_le90_1x.json --batch-size 4

# Enable mixed precision training
python tools/train.py --config configs/oriented_rcnn/dota_le90_1x.json --use-amp

# Disable mixed precision training
python tools/train.py --config configs/oriented_rcnn/dota_le90_1x.json --no-amp

For checkpoints, edit the JSON checkpoint section: load_from_checkpoint, load_from_experiment, discover_previous_run, resume_from_checkpoint_epoch, etc. See configs/config.schema.json and oriented_det/train/README.md.

Troubleshooting: GET was unable to find an engine to execute this computation

This usually comes from cuDNN during convolution forward/backward (not from oriented-det code). Try in order:

  1. Disable cuDNN benchmark (often fixes bad algorithm selection):
    ORIENTED_DET_CUDNN_BENCHMARK=0 python tools/train.py --config configs/.../config.json
  2. Disable AMP: python tools/train.py --config configs/.../config.json --no-amp
  3. LD_LIBRARY_PATH: an older system CUDA/cuDNN can shadow libraries shipped with your PyTorch install. Compare the variable in shells where training works vs fails; try unset LD_LIBRARY_PATH temporarily (common with conda + manual CUDA).
  4. Align PyTorch / CUDA / driver using python -m torch.utils.collect_env.

Troubleshooting: NCCL ALLREDUCE / watchdog timeout after “Computing final mAP…”

Rank 0 runs full mAP inside evaluate() (can take many minutes with large val sets). Other ranks skip mAP and used to exit train() first and call destroy_process_group() while rank 0 was still computing → broken process group and a long NCCL timeout. Fixed in oriented_det/train/engine.py with a dist.barrier() after final mAP when using DDP. If you still see timeouts, increase NCCL_TIMEOUT or set evaluation.val_map_at_end to false and run a separate single-GPU eval on the best checkpoint.

Configuration: Configuration is loaded from JSON files in the configs/ directory. Each config file includes:

  • Dataset paths (data_root, train_tiles_dir, val_tiles_dir)
  • Model configuration (backbone, anchor_scales, anchor_ratios, etc.)
  • Training hyperparameters (batch_size, learning_rate, num_epochs, etc.)
  • Loss configuration (class weighting, focal loss; focal_weighted also scales FCOS/RetinaNet sigmoid focal)
  • Evaluation settings
  • Checkpoint settings

See configs/ directory for reference configs for different model types.

publish_checkpoint.py

Prepare a training checkpoint for Hub distribution: strip optimizer state, save CPU tensors, append SHA-256[:8] to the filename (MMDet-style).

python tools/publish_checkpoint.py \\
  runs/oriented_rcnn/20260911-102320/checkpoints/best_mAP_0.80.pth \\
  pretrained/oriented_rcnn_r50_fpn_dota_le90_3x
# -> pretrained/oriented_rcnn_r50_fpn_dota_le90_3x-<hash8>.pth

Copy the experiment config.json and train.log beside the published weight as <weight-stem>.json and <weight-stem>.log (same hash stem as the .pth).

Update oriented_det/pretrained/manifest.json with the new filename and sha256, then upload to the Hub repo (make upload-pretrained uploads .pth, sidecar .json, and .log).

lr_finder.py

Learning rate finder: runs a short training sweep with exponentially increasing learning rate, records loss vs LR, stops early when EMA-smoothed loss exceeds stop_mult × the best smoothed loss so far (fastai LRFinder / stop_div), then truncates the recorded trace after the first raw divergence (loss > stop_mult × running minimum before that step) before computing suggestions. Heuristics use a trimmed trace (skip first num_steps//10 and last 5 points, like Learner.lr_find). Prints valley (default primary), steep, minimum (LR at min loss ÷ 10), and slide when they succeed; primary order: valley → steep → minimum → slide, else geometric mid of the sweep. Single-GPU only. Uses the same config and data as training.

Usage:

# Basic run (uses config's batch size and AMP)
python tools/lr_finder.py --config configs/oriented_rcnn/dota_le90_1x.json

# Custom sweep length and save plot
python tools/lr_finder.py --config configs/.../config.json --num-steps 150 --output lr_finder.png

# Disable AMP for the sweep; restore model state after (so you can train without reloading)
python tools/lr_finder.py --config configs/.../config.json --no-amp --restore

Options:

  • --config — Path to training config JSON (required)
  • --batch-size — Override batch size
  • --num-steps — Number of steps in the LR sweep (default: 100)
  • --start-lr / --end-lr — LR range (default: 1e-7 to 10.0)
  • --no-amp — Disable mixed precision for the sweep
  • --restore — Restore model weights after the sweep
  • --output — Save loss-vs-LR plot (e.g. lr_finder.png; marks divergence cut when used)
  • --no-early-stop — Run all num-steps even if loss explodes (truncation for suggestions still applies unless you also raise --stop-mult very high)
  • --stop-mult K — Early stop and divergence cut when loss (or smoothed loss for early stop) exceeds K × best-so-far (default: 4)
  • --smooth-beta — EMA for smoothed loss during early stop, 0 ≤ beta < 1 (default: 0.98)

Use the printed primary LR (or another heuristic) in your config’s training.learning_rate; the tool also prints values scaled to the config batch size when the sweep used a different --batch-size. Scale further by world size / gradient accumulation as in train.py if needed. The model is updated during the sweep; for clean training, start from scratch or load a checkpoint.

From the repo root: make lr-finder or make lr-finder CONFIG=configs/.../config.json (optional: OUTPUT=lr_finder.png). With no CONFIG, it uses the Makefile default. The sweep uses that file's batch size.

train.py (continued)

--wizard: odet train --config … --wizard (or make wizard) scans the training split and prints geometry/density stats plus config nudges. FPN/box-reg advice is class-agnostic: it uses pooled GT width vs finest FPN stride (cells on P3/P4/…), not class names. Small boxes (few cells, or a non-trivial share under 2 cells) get “keep finest level + decoded kfiou”; larger boxes do not. Anchor-ratio and target_stds nudges are printed only for Oriented R-CNN, Rotated Faster R-CNN, and Rotated RetinaNet. No run directory is created.

Features:

  • Config-based training (all parameters in JSON files)
  • Supports multiple model types (Rotated Faster R-CNN, Oriented R-CNN, Rotated RetinaNet, Rotated FCOS)
  • Command-line parameter overrides (batch size, AMP, etc.)
  • Load DOTA dataset (automatically discovers classes)
  • Automatic checkpointing and experiment management
  • Learning rate scheduling with warmup
  • Mixed precision training (configurable)
  • Gradient accumulation
  • Class distribution analysis
  • Automatic resume from last experiment

save_predictions.py

Runs inference on a dataset split, writes predictions.json, and (when diagnostics are enabled) produces:

  • analysis_iouXX.json: PR/F1 sweep + per-class AP (class_aps) and MMRotate-style stats (class_metrics: gts, dets, recall, ap per class) + gt_alignment_metrics (global and per-class mean best IoU vs raw detections)
  • model_analysis_<timestamp>.md: human-readable report including a per-class gts / dets / recall / AP table and a GT alignment (mean best IoU) section

Note: This tool requires a properly formatted DOTA dataset with tiled images:

dota_root/
  train/
    tiles_1024/
      images/
        P0001_0_0.png
        ...
      labels/
        P0001_0_0.txt
        ...
  val/
    tiles_1024/
      images/
        ...
      labels/
        ...

See tools/tile_dota.py to create tiles from large DOTA images.

Hub zoo (no runs/ directory):

odet preds --checkpoint hf://oriented_rcnn_dota_le90_3x --data-split val --no-diagnostics
odet preds --checkpoint hf://oriented_rcnn_dota_le90_3x --data-split test \
  --test-dir /path/to/data/DOTA-v1.0/test --no-diagnostics

oriented_det.runtime.inference

Run inference with trained models.

Usage:

# Basic inference
python -m oriented_det.runtime.inference image.jpg \
    --checkpoint checkpoints/best.pth \
    --output detections.png

# With custom thresholds
python -m oriented_det.runtime.inference image.jpg \
    --checkpoint checkpoints/best.pth \
    --score-threshold 0.7 \
    --nms-threshold 0.5 \
    --output detections.png

# Specify model type and classes
python -m oriented_det.runtime.inference image.jpg \
    --checkpoint checkpoints/best.pth \
    --model-type oriented_rcnn \
    --num-classes 15 \
    --class-names plane ship vehicle ... \
    --output detections.png

# With config: pad/tile when image size ≠ model input (e.g. large 2048×2048 or small 512×512 vs 1024×1024)
python -m oriented_det.runtime.inference large_image.png --checkpoint best.pth --config runs/.../config.json --output out.png
# Optional: --overlap-pixels 200 (default) or --overlap-ratio 0.2
# Window batch default is 8; override with --window-batch-size or ORIENTED_DET_WINDOW_BATCH_SIZE

Features:

  • Load trained models from checkpoints
  • Preprocess images
  • Run inference
  • Apply NMS to filter detections
  • Visualize results with labels
  • Print detection summaries
  • Padded-canvas / sliding-window inference: With --config, inference always uses pad/tile windows to the model input (preprocessing.target_size): zero-pad small images, tile large ones (last row/column flush to the image edge, same as tile_dota.py); no full-image resize and no rescaling of box coordinates afterward. Default per-window margin is 0 (keep overlap copies, then NMS). Pass --ignore-margin-pixels to drop detections whose centroid lies in the overlap band (interior window sides only — full-image borders are exempt). Detections are merged and NMS runs in original image coordinates. Use --overlap-pixels (default 200 per axis, aligned with tile_dota.py) or --overlap-ratio in [0,1) (if set, overrides pixel overlap) when multiple tiles are used.
  • Sliding-window batching: Sliding-window inference batches multiple windows per forward. Default: 8 on CUDA/MPS and 4 on CPU. Override with --window-batch-size or ORIENTED_DET_WINDOW_BATCH_SIZE=16. Set ORIENTED_DET_WINDOW_BATCH_SIZE=auto to probe the largest empty-canvas batch (cached). That probe overestimates two-stage VRAM on dense tiles and can OOM mid-run.

save_predictions.py

Run inference on a validation (or train) split, save predictions to JSON, and optionally compute mAP in the same process (--no-diagnostics skips GPU-side metrics). Use make eval-val for inference plus offline metrics in one step. On DOTA, that val split is leaky (train+val tiles); the real test is Task 1 (make dota-submit). On HRSC, eval-val is held-out ImageSets test. On FAIR1M, it is held-out official val. After make preds, run make metrics (or python tools/save_predictions.py --metrics-from-json path/to/dir) to recompute mAP/PR with different --iou-threshold, --metrics-margin-pixels, PR sweep steps, etc., without re-running inference (metrics rebuild GT/det maps from predictions.json). Uses oriented_det.runtime.inference.run_inference_auto: resize_mode: pad (HRSC2016) always runs one training-style whole-image forward (scale long edge to target_size, then pad). fixed / crop (DOTA) use a single training-style forward when the image fits the canvas, and sliding windows when it is larger (last tiles flush to the image edge). --window-margin-pixels default 0 (keep overlap copies, then NMS). Supports override of the validation folder for non-tiled DOTA val (e.g. to compare with literature mAP on full-size images). Model construction reads model.fpn_returned_layers, model.fpn_strides, and model.trainable_layers / frozen_stages from the experiment config.json so the backbone matches training (required when FPN does not use all ResNet stages, e.g. [1,2,3] without C5).

GPU / cuDNN: If every val image fits in one model tile, inference is already one forward per image (no window batching). If a large raster still OOMs, lower ORIENTED_DET_WINDOW_BATCH_SIZE (see oriented_det/runtime/inference.py). ORIENTED_DET_CUDNN_BENCHMARK=0 can help if cuDNN algorithm search fragments memory.

Label / image coordinates: For layouts with images/ and labels/ (or labelTxt/), each basename.txt must describe objects in the same coordinate system as basename.jpg (or .png)—pixel coords on that raster, top-left origin. The tool does not rescale or reproject labels to match the image.

Usage:

# Default: use config's val_tiles_dir, auto-detect latest experiment
python tools/save_predictions.py

# Override val folder (e.g. non-tiled DOTA val with full-size images)
python tools/save_predictions.py --config runs/.../config.json --val-dir /path/to/data/DOTA-v1.0-tiled/val
# Pad/tile windows always; mAP compares predictions to labels in the images' pixel space (labels must match each image file).

# Overlap ratio between windows when the image needs multiple tiles (default 0.2)
python tools/save_predictions.py --config runs/.../config.json --val-dir /path/to/non-tiled/val --overlap-pixels 200
python tools/save_predictions.py --config runs/.../config.json --val-dir /path/to/non-tiled/val --overlap-ratio 0.25

Options: --val-dir overrides config.dataset.val_tiles_dir so you can point to a non-tiled validation folder (e.g. DOTA full-size images in images/ and labels/ or labelTxt/) while the config still references the tiled val. --data-split test uses labeled dataset.test_tiles_dir(s) or dataset.test_split when the config has a test split (make eval-test, --require-test-split). Without that split, or with --test-dir, it lists unlabeled official test rasters (data_root/test or test/images/ or a flat png/jpg folder) for Task 1. Missing labels yield empty GT (use --no-diagnostics). --no-diagnostics skips mAP/PR/analysis (inference-only JSON). --metrics-from-json PATH loads an existing predictions.json (PATH may be the file or its directory), recomputes metrics from stored boxes/scores/GTs, writes analysis_*.json / plots beside it, and refreshes metadata.diagnostics. Sliding-window overlap: --overlap-pixels (omit to use production.overlap_pixels from the experiment config when set, else 200) or --overlap-ratio in [0,1) (if set, overrides pixels). Last tiles flush to the image edge. Per-window centroid margin: --window-margin-pixels (default 0, keep overlap copies then NMS). Metrics edge margin: eval-val defaults to 0 (every GT and detection is scored), including make metrics / --metrics-from-json. --metrics-margin-pixels sets a positive band that drops centroids in [0, margin) or (W-margin, W] and keeps the tile interior for metrics only. Eval-val does not read production.ignore_margin_pixels, tile overlap, or a margin stored in predictions.json. Deploy / image_demo still use production.ignore_margin_pixels (null means dataset.overlap / 2). If --nms-threshold is omitted, the tool uses config.model.final_nms_iou_threshold (fallback: 0.5; legacy nms_threshold is migrated on load). If --iou-threshold is omitted, mAP / PR matching uses effective_eval_metric_thresholds so production.iou_threshold overrides evaluation.iou_threshold when set, same merge order as validation during training—this is rotated GT–det IoU, not NMS IoU. If --score-threshold is omitted, the post-NMS filter for run_inference_auto and diagnostics uses resolve_preds_score_threshold (CLI → evaluation.preds_score_threshold → 0.05), not production.score_threshold or train-val evaluation.train_val_score_threshold. Logs print mAP50-style names (e.g. Final mAP50: …) and spell out NMS IoU separately so it is not confused with DOTA’s 0.1 NMS.

Inference-time knob overrides (without editing config.json): You can override the model’s proposal / prefilter behavior for evaluation-only runs:

  • --inference-pre-nms-score-threshold: overrides model.inference_pre_nms_score_threshold (prefilter before final/merge NMS)
  • --rpn-pre-nms-top-n: overrides model.rpn_pre_nms_top_n
  • --rpn-post-nms-top-n: overrides model.rpn_post_nms_top_n
  • --rpn-nms-threshold: overrides model.rpn_nms_threshold (proposal NMS)
  • --nms-class-agnostic / --no-nms-class-agnostic: overrides model.nms_class_agnostic

Progress (tqdm): Bars use oriented_det.utils.tqdm_progress_stream() so they can render on the real terminal when stderr is piped (e.g. 2>&1 | tee preds.log), like training’s progress_stream—log files stay line-based without \\r spam; mAP/PR use the same stream.

Precision-recall and F1 analysis: save_predictions.py computes a dataset-level precision-recall curve by sweeping score thresholds, selects the best global threshold using F1, and writes:

  • analysis_iou0.50.json (threshold curve + best-threshold block + confusion matrix + per-image metrics including precision/recall/F1/F2 + gt_alignment_metrics)
  • pr_curve.png (precision vs recall)
  • threshold_metrics.png (precision/recall/F1 vs threshold)
  • model_analysis_<timestamp>.md (timestamped model report with model/date/data/metrics, per-class gts/dets/recall/AP table like MMRotate, per-class mean best IoU (GT alignment) table, optional per-class best-threshold table (F1), confusion matrix, and artifact references)

The confusion matrix is computed at the best global F1 threshold. Rows are GT classes and columns are predicted classes; the extra False Positive row contains unmatched detections, and the extra Missed column contains unmatched GTs.

Sweep controls:

  • --pr-threshold-min (default 0.0)
  • --pr-threshold-max (default 1.0)
  • --pr-threshold-step (default 0.05)
  • --pr-iou-threshold (default: uses --iou-threshold; lets PR/F1 matching IoU differ from mAP IoU)

Per-class score thresholds: For save_predictions.py, merged evaluation.* + production.* per-class floors come from merge_per_class_score_thresholds. Global score for preds uses resolve_preds_score_threshold: val reads evaluation.val_score_threshold, test reads evaluation.test_score_threshold (null → 0.05). Production is deploy only. predictions.json metadata records the applied score_threshold and per_class_score_threshold.

production.output_classes: Post-NMS class allowlist (case-insensitive). Same field for odet preds, image_demo, deploy/Docker, and ONNX export. Excluded classes still compete in NMS; only the returned list is trimmed. Prefer this over impossible per-class score floors (e.g. 1.1).

Per-class best threshold analysis: With --per-class-threshold-analysis, the analysis JSON also includes best_threshold_per_class (best F1 per class over the same threshold grid). This is expensive on large datasets.

Per-tile metrics CSV: Pass --tile-metrics-csv path.csv (relative paths are resolved under the run output directory). Writes one row per image (columns match per_image_metrics in the analysis JSON), for joining with training oversampling (dataset.tile_metrics_csv in config). Tiles with no ground truth and no predictions above the chosen global threshold get precision = recall = F1 = F2 = 1.0 (correct empty image), so they are not treated as low-F1 failures. Training still ignores tp=fp=fn=0 rows as hard tiles when reusing older CSVs that stored F1=0 for those cases.

Hard-tile oversampling in training: From the repo root, make train-preds runs the train split (latest experiment) and writes tile_metrics.csv under <latest_exp>/train_tile_eval/ by default (override with SAVE_TRAIN_PRED_OUT=/path). Equivalent manual command: python tools/save_predictions.py --data-split train --tile-metrics-csv tile_metrics.csv .... Then set in your training config: dataset.tile_metrics_csv to that CSV path, plus optional hard_tile_metric_column (default f1), hard_tile_threshold (default 0.8), hard_tile_oversample_factor (default 2.0). Single-GPU training uses WeightedRandomSampler; multi-GPU expands the dataset index list so DistributedSampler sees more draws of hard tiles. Optional dataset.drop_easy_empty_tiles: true (requires the CSV) removes train tiles with tp=fp=fn=0 before max_train_samples and oversampling, so you can keep filter_empty_gt: false in the loader: easy empty tiles leave the epoch, empty tiles with false positives stay and can be oversampled. Tiles with no CSV row are kept. Validation is unchanged.

Class-tile oversampling in training: Optional second path that upweights train tiles from ground-truth class presence only (no metrics CSV). Set dataset.class_tile_oversample_classes to a list of class_name strings (case-sensitive exact, same as class_map / map_labels outputs), plus optional class_tile_oversample_factor (default 1.0 = no extra weight) and class_tile_oversample_min_count (default 1). A tile matches if it has at least that many remaining GT boxes whose class_name is in the list (after the loader’s ignore / difficult / lookalike filtering). Lookalike routing labels are never a match. Unknown names in the list are warned once and ignored. null or [] disables. Reuses the same WeightedRandomSampler / DDP index expansion as hard-tile oversampling: per-index weight starts at 1.0, hard-tile (when the CSV is set) applies as before, then class-matched indices are multiplied by class_tile_oversample_factor. Both can be on: final_weight = hard_weight * class_weight. Example:

"dataset": {
  "class_tile_oversample_classes": ["class-a", "class-b"],
  "class_tile_oversample_factor": 3.0,
  "class_tile_oversample_min_count": 1
}

make preds / make metrics (Makefile): The root Makefile does not pass score, IoU, overlap, or NMS overrides. make preds runs tools/save_predictions.py with --no-diagnostics only; the val score floor is evaluation.val_score_threshold; make eval-test uses evaluation.test_score_threshold or 0.05, NMS IoU prefers evaluation.final_nms_iou_threshold, and tiling uses production.overlap_pixels. For tiled DOTA, all tiles under the split roots are included (dataset.filter_empty_gt is not applied at inference; training may still drop empty tiles). make metrics runs --metrics-from-json with no extra flags: mAP/PR reuse predictions.json metadata (the values written at inference time). To re-run metrics with different thresholds, call python tools/save_predictions.py --metrics-from-json <dir> --score-threshold … yourself.

app.py

Gradio app to browse predictions from save_predictions.py, explore a DOTA dataset, or edit OBB CSV annotations with an optional read-only reference overlay. Prediction and ground-truth outlines in predictions/dataset mode are drawn after zoom, so --line-width (default 1) is the stroke in screen pixels and stays the same at 1×, 2×, and 4×. The same control is the Line width (px) slider in the app. The CSV editor still uses oriented_det.utils.viz.DEFAULT_LINE_WIDTH.

The app includes a small Gradio 6.8 compatibility patch so cleared/null slider payloads fall back to the slider default instead of crashing during slider preprocessing.

Predictions mode (requires a predictions directory from save_predictions.py):

python tools/app.py --mode predictions --predictions-dir predictions/20250101_120000
# Optional: --data-root /path/to/data/DOTA-v1.0-tiled --threshold 0.3 --line-width 1 --port 7860

Dataset mode (browse DOTA labels without predictions):

python tools/app.py --mode dataset --data-root /path/to/data/DOTA-v1.0-tiled --tiles-dir train/tiles_1024

CSV annotation editor (finalize HBB→OBB conversions or manual QA):

python tools/app.py --mode csv \
  --data-root /path/to/dataset \
  --annotations-csv /path/to/dataset/annotations_oriented.csv \
  --reference-csv /path/to/dataset/annotations.csv
  • Green = read-only reference (--reference-csv, e.g. original horizontal GT).
  • Red = editable layer (--annotations-csv); yellow outline = selected box.
  • Edit class, cx/cy/width/height/angle fields and click Apply changes.
  • Add box, Delete selected, Copy reference → editable, then Save CSV to write the editable file.

Related pipeline tools: generate_oriented_annotations.py, filter_predictions_by_gt.py, compare_hbb_obb_counts.py (see hbb_to_obb.py).

dataset_stats.py

Dataset sanity checks, statistics (class distribution, annotations per image, image dimensions), and per-channel normalization mean/std for the dataset defined by your training config. Use the output mean/std in preprocessing.normalize_mean and preprocessing.normalize_std; values are in [0, 1] scale (after ToTensor).

Usage:

# Full run (sanity checks + stats + normalization)
python tools/dataset_stats.py --config configs/.../config.json

# Stats and sanity only (no normalization; faster)
python tools/dataset_stats.py --config path/to/config.json --stats-only

# Normalization only (legacy behavior)
python tools/dataset_stats.py --config path/to/config.json --normalization-only

# Quick run on a subset
python tools/dataset_stats.py --config path/to/config.json --max-samples 500

# Use validation split
python tools/dataset_stats.py --config path/to/config.json --split val

Sanity checks: Missing images, failed image loads, empty annotations, duplicate paths. Stats: Class counts, annotations per image (min/max/mean), image width/height (min/max/mean). Output: Prints normalization normalize_mean and normalize_std and a JSON snippet for preprocessing when normalization is run.

preview_augmentation.py

Preview training-time augmentations from an experiment config before a long run. Loads the train (or val) split, applies the same collate path as tools/train.py (resize, optional random flips, optional random rotate, optional Albumentations), and writes comparison grids with oriented boxes drawn on each panel.

Use this to sanity-check augmentation.json / recipe overrides, flip / rotate settings in preprocessing, and enable_albumentation without starting training.

Usage:

# Recipe or resolved run config
python tools/preview_augmentation.py --config configs/oriented_rcnn/dota_le90_1x.json

# More tiles and random variants per tile
python tools/preview_augmentation.py --config runs/oriented_rcnn/20260616-030231/config.json --num-images 4 --variants 6

# Fixed dataset indices; Albumentations column without flips
python tools/preview_augmentation.py --config configs/.../config.json --indices 0,12,48 --include-albumentations-only

# Custom output directory
python tools/preview_augmentation.py --config configs/.../config.json --output-dir /tmp/aug_preview

Options:

  • --config — Training recipe or resolved config.json (required)
  • --output-dir — Where to write PNGs (default: previews/augmentation/<config_stem>/ under the repo root)
  • --split — train or val (default: train)
  • --num-images — Random tiles to preview (default: 3)
  • --variants — Random augmented variants per tile (default: 4)
  • --seed — RNG seed for tile and augmentation sampling (default: 42)
  • --indices — Comma-separated dataset indices (overrides --num-images random sampling)
  • --include-albumentations-only — Add a column with Albumentations only (no random flips)

Output: For each tile, one row PNG (00042_<stem>.png) with panels:

  1. baseline — resize only, no augmentation
  2. albumentations only — when --include-albumentations-only and enable_albumentation is true
  3. train aug #N — full training collate (flips + random rotate + Albumentations when enabled)

Also writes grid_all.png (all rows stacked) and meta.json (config path, indices, seed, variants).

Config loading: Uses lenient parsing when the config contains unknown keys (e.g. older run configs); unknown section fields are dropped so preview still runs. Supports DOTA tiled datasets, Airbus Playground, HRSC2016, and FAIR1M (dataset.format).

Typical workflow: Run dataset_stats.py for normalization and class balance, then preview_augmentation.py to verify augmentations look reasonable on real tiles.

generate_airbus_playground_csv.py

Build annotations and split CSVs under an Airbus Playground export root. By default both files are dated as a pair (annotations_YYYYMMDD.csv and split_YYYYMMDD.csv, UTC) so reruns on another day do not overwrite a previous snapshot; pass --annotations-file / --split-file for fixed names (if only one is dated, the other is inferred from the same date). Splits are integer fold ids (default 10 folds): groups (dataset_id, zone_id, image_id) are shuffled with --seed then assigned 0 .. num_splits-1 in round-robin order. Fold 0 is the conventional validation fold; rotate validation by setting dataset.val_split_id in your training JSON. After generation, set dataset.annotations_file and dataset.split_file in your training config to the printed filenames.

Airbus Playground (CSV generation → make wizard → make lr-finder): Data guide.

Usage:

python tools/generate_airbus_playground_csv.py --data-root /path/to/playground_export
python tools/generate_airbus_playground_csv.py --data-root /path/to/export --seed 42
python tools/generate_airbus_playground_csv.py --data-root /path/to/export --ignore-label Confuser --map-label taxi=car
python tools/generate_airbus_playground_csv.py --data-root /path/to/export \
  --difficult-tag 'Partially Hidden' --map-label 'car, van and pickup=car' --map-label 'truck and bus=truck'

--difficult-tag (repeatable) strips that exact Playground tag from class_name and writes difficult=1. Pair with training dataset.difficult_strategy: "ignore" and the same dataset.difficult_tags so existing CSVs still work without regenerating.

playground_to_dota.py

Export Airbus Playground export folders to DOTA-format directories (images + .txt labels). Converts polygon annotations to DOTA OBB format. Optionally splits output into train/val using a group-level ratio (--val-ratio) or an existing split.csv from generate_airbus_playground_csv.py. For CSVs with integer fold ids, pass --val-split-id (default 0) to choose which fold is written under val/.

Usage:

# Single output dir (no split)
python tools/playground_to_dota.py --data-root /path/to/playground_export --output-dir /path/to/dota_out

# Train/val split by image group
python tools/playground_to_dota.py --data-root /path/to/export --output-dir /path/to/dota_out --val-ratio 0.2 --seed 42

# Use existing split CSV (integer folds: val fold 0 unless --val-split-id is set)
python tools/playground_to_dota.py --data-root /path/to/export --output-dir /path/to/dota_out --split-file /path/to/export/split.csv
python tools/playground_to_dota.py --data-root /path/to/export --output-dir /path/to/dota_out --split-file /path/to/export/split.csv --val-split-id 2

# Label options
python tools/playground_to_dota.py --data-root /path/to/export --output-dir /path/to/dota_out --ignore-label Confuser --map-label "taxi=car"
python tools/playground_to_dota.py --data-root /path/to/export --output-dir /path/to/dota_out \
  --difficult-tag 'Partially Hidden' --map-label 'car, van and pickup=car'

# Dry run (report stats only)
python tools/playground_to_dota.py --data-root /path/to/export --output-dir /path/to/dota_out --dry-run

ossdd_fix_tiff.py

Rewrite photometric interpretation 34892 (DNG LinearRaw) to 1 (MinIsBlack) on the OSSDD 700×700 train chips. Pixel bytes stay put. Pillow refuses 34892, so ossdd_to_dota.py cannot read those chips until this has run. Val and test chips are already MinIsBlack and are skipped.

Usage:

python tools/ossdd_fix_tiff.py --data-root /path/to/data/OSSDD --dry-run
python tools/ossdd_fix_tiff.py --data-root /path/to/data/OSSDD

ossdd_to_dota.py

Export OSSDD (Sentinel-1 GRD, Hammer et al. 2026) float chips and rotated-box text to DOTA PNG + labels/. Clips non-positive amplitudes and values above 20000, applies log10, then per-chip min-max. Repeats the gray chip to RGB. Default polarization is VH.

Usage:

python tools/ossdd_to_dota.py --data-root /path/to/data/OSSDD --output-dir /path/to/data/OSSDD-dota --polarization VH

Recipes: configs/rotated_rtmdet/ossdd_le90_vh_1x_s.json, configs/rotated_fcos/ossdd_le90_vh_3x.json, configs/rotated_faster_rcnn/ossdd_le90_vh_3x.json. The FCOS and Faster R-CNN 3× recipes inherit a 1× finetune in the same folder.

hrsc_to_dota.py

Export official HRSC2016 XML/BMP splits to DOTA-format PNG + .txt folders. Native training uses dataset.format: hrsc2016 and does not require this step; use it when you want DOTA loaders or odet tile-dota.

Usage:

odet hrsc-to-dota --data-root /path/to/data/HRSC2016 --output-dir /path/to/data/HRSC2016-dota
python tools/hrsc_to_dota.py --data-root /path/to/data/HRSC2016 --output-dir /tmp/hrsc_dota --splits trainval,test

See Data guide — HRSC2016.

fair1m_to_dota.py

Export FAIR1M XML + images to DOTA-format image + .txt folders. Default --image-format original copies JPEG/PNG (TIFF → PNG). Prefer this + odet tile-dota over whole-image training. Official FAIR1M-1.0 at /path/to/data/FAIR1M already has labeled train/val — omit --val-fraction. Use --val-fraction only when the dump has no val. Point recipes at .../tiles_1024, not the parent split folder.

Usage:

odet fair1m-to-dota --data-root /path/to/data/FAIR1M --output-dir /path/to/data/FAIR1M-dota \
  --splits train,val
odet tile-dota /path/to/data/FAIR1M-dota/train --tile-size 1024 --overlap 200 --min-overlap 0.7
odet tile-dota /path/to/data/FAIR1M-dota/val --tile-size 1024 --overlap 200 --min-overlap 0.7

See Data guide — FAIR1M.

coco_to_dota.py

Export COCO instance polygons to DOTA-format image + .txt folders. n-gons become a min-area rectangle (OBB only). Native HRSID/SSDD training does not require this.

Usage:

odet coco-to-dota --ann-file train2017.json --image-dir images --output-dir /tmp/coco_dota --output-split train
odet coco-to-dota --data-root /path/to/data/HRSID_JPG --output-dir /path/to/data/HRSID-dota --splits train,test

See Data guide — HRSID.

ssdd_to_dota.py

Export SSDD (VOC XML, COCO, or DOTA layouts) to DOTA-format image + .txt folders. Native training uses dataset.format: ssdd. XML robndbox angles are degrees. Grayscale SAR is written as RGB.

Usage:

odet ssdd-to-dota --data-root /path/to/data/Official-SSDD-OPEN --output-dir /path/to/data/SSDD-dota
python tools/ssdd_to_dota.py --data-root /path/to/data/Official-SSDD-OPEN --output-dir /tmp/ssdd_dota --splits train,test

See Data guide — SSDD.

dota_task1_submit.py

Write DOTA v1.0 Task 1 Task1_{class}.txt files + a zip for the official evaluation server. Test labels are not public; there is no local test mAP.

Convert an existing predictions.json (from odet preds --data-split test --no-diagnostics), or run unlabeled test inference then convert. Prefer a Hub zoo slug (hf://…) so you do not need a local runs/ directory; the checkpoint sidecar JSON is loaded automatically. Classes with zero detections get a dummy low-score line (the server rejects empty files). Use --no-dummy only if you will add lines yourself.

Usage:

# Hub zoo (recommended): sidecar config, unlabeled official test
odet dota-submit --checkpoint hf://oriented_rcnn_dota_le90_3x \
  --test-dir /path/to/data/DOTA-v1.0/test --output-dir work_dirs/Task1_orcnn
make dota-submit CHECKPOINT=hf://oriented_rcnn_dota_le90_3x \
  TEST_DIR=/path/to/data/DOTA-v1.0/test OUT=work_dirs/Task1_orcnn

# Other DOTA slugs: hf://rotated_faster_rcnn_dota_le90_1x hf://rotated_faster_rcnn_dota_le90_3x
#   hf://rotated_fcos_dota_le90_1x  hf://rotated_retinanet_dota_le90_1x hf://rotated_retinanet_dota_le90_3x
#   hf://rotated_retinanet_dota_le90_1x_hbb hf://rotated_retinanet_dota_le90_3x_hbb

# Local training run
odet dota-submit --experiment-dir runs/oriented_rcnn/<id> \
  --test-dir /path/to/data/DOTA-v1.0/test --output-dir work_dirs/Task1_orcnn

# Existing predictions.json
odet preds --checkpoint hf://oriented_rcnn_dota_le90_3x --data-split test \
  --test-dir /path/to/data/DOTA-v1.0/test --no-diagnostics
odet dota-submit --from-json predictions/<ts>/predictions.json --output-dir work_dirs/Task1_orcnn
make dota-submit FROM_JSON=predictions/<ts> OUT=work_dirs/Task1_orcnn

Score 0.05 follows the eval-val resolver. odet dota-submit forces final NMS 0.1 (Hub sidecars often still have production.final_nms_iou_threshold 0.5). Inference on full test rasters uses sliding windows (1024 / overlap 200): last tiles flush to the image edge (same as tile_dota.py), keep overlap copies (per-window margin default 0), then NMS. That is live ResultMerge-style, not MMRotate’s on-disk pre-tile merge. Pass --window-margin-pixels to drop the overlap band. Use this zip to compare oriented-det checkpoints on the hidden test set; do not subtract MMRotate zoo 71.28 / 73.40 / 75.69 without that distinction.

Upload the zip (15 Task1_*.txt at the archive root) to DOTA-v1.0 Task 1. On server failure, the site allows emailing dotawebsite3@gmail.com with team/institute. Task 2 (HBB) is out of scope.

See Data guide — official test / Task 1.

tile_dota.py

Tile large DOTA format images into smaller patches for training.

Usage:

# Basic tiling (creates 1024x1024 tiles with 200px overlap by default)
python tools/tile_dota.py /path/to/dota/train

# Custom tile size and overlap
python tools/tile_dota.py /path/to/dota/train \
    --tile-size 512 \
    --overlap 128

# Adjust minimum overlap ratio for keeping objects
python tools/tile_dota.py /path/to/dota/train \
    --min-overlap 0.5

# Overwrite existing tiles
python tools/tile_dota.py /path/to/dota/train --overwrite

# Tile format: auto (JPEG→jpg, PNG/TIFF→png), or force png/jpg
python tools/tile_dota.py /path/to/dota/train --output-format jpg --jpeg-quality 95

# Legacy: last row/column may extend past the image (zero-padded tiles)
python tools/tile_dota.py /path/to/dota/train --pad-edge-tiles

Features:

  • Tile large aerial/satellite images into manageable patches
  • Process oriented bounding box annotations (DOTA format)
  • Configurable tile size and overlap
  • Minimum overlap ratio filtering (default 0.7, aligned with MMRotate iof_thr; keeps objects with >= 70% area inside the tile)
  • Automatic padding for images smaller than tile size
  • By default, last row/column of tiles align on the image edge (no right/bottom zero-padding); use --pad-edge-tiles for the old stride-only edge behavior
  • Computes minimum rotated rectangles for truncated objects
  • Outputs official DOTA annotation format (comma-separated)
  • Reads PNG, JPEG, TIFF, and BMP; default --output-format auto writes JPEG tiles from JPEG sources and PNG otherwise (--output-format png|jpg to force; --jpeg-quality default 95)

Input Structure:

data_dir/
  images/
    P0001.png
    P0002.jpg
    ...
  labels/
    P0001.txt
    P0002.txt
    ...

Output Structure:

data_dir/tiles_{size}/
  images/
    P0001_0_0.png
    P0001_960_0.png
    P0002_0_0.jpg
    ...
  labels/
    P0001_0_0.txt
    P0001_960_0.txt
    P0002_0_0.txt
    ...

Note: This tool is particularly useful when:

  • Working with large DOTA v1.0 or v2.0 images (typically 800-20000 pixels)
  • Training models that require fixed input sizes
  • Need to control memory usage during training
  • Want to apply sliding window inference

dota_labels_to_comma.py

Convert DOTA label .txt files from space-separated to official comma-separated format in place.

Usage:

# Convert all .txt in a labels folder
python tools/dota_labels_to_comma.py /path/to/labels

# Dataset root (uses labels/ or labelTxt/ if present)
python tools/dota_labels_to_comma.py /path/to/dataset

# Dry run (no writes)
python tools/dota_labels_to_comma.py /path/to/labels --dry-run

# Backup originals as .txt.bak
python tools/dota_labels_to_comma.py /path/to/labels --backup

Accepts both space- and comma-separated input; writes official format. Keeps metadata lines (e.g. imagesource:, gsd) and empty lines unchanged.

Requirements

All tools require the core dependencies:

uv pip install torch torchvision Pillow

For training and inference, ensure you have:

  • PyTorch with CUDA support (optional, for GPU acceleration)
  • Properly formatted DOTA dataset (for training)

Customization

These tools are designed to be starting points for real-world use. You can customize them for:

  • Different datasets (modify data loading)
  • Custom augmentation (add transforms)
  • Different model architectures (modify model creation)
  • Custom evaluation metrics (add to training loop)

measure_sampled_riou_error.py

Compare sampling-based GPU rIoU (oriented_box_iou_gpu) against exact Shapely polygon IoU on stratified synthetic pairs (tiny/small/medium/large squares, elongated ships, thin slivers). Reports absolute / relative error percentiles overall, by category, and by exact-IoU bin — use it to tune geometry defaults in oriented_det/ops/gpu_ops.py (target_spacing_px, min_samples, max_samples, min_points_short).

Requires: Shapely (core dependency).

# Default geometry (2 px spacing, 25…1024 samples), 3000 pairs
python tools/measure_sampled_riou_error.py

# More pairs + CSV export
python tools/measure_sampled_riou_error.py --pairs 5000 --seed 0 --csv /tmp/riou_error.csv

# Sweep target spacing to tune further
python tools/measure_sampled_riou_error.py --pairs 2000 --sweep-spacing 1.5 2 3 4

# Override caps (must stay perfect squares for min/max)
python tools/measure_sampled_riou_error.py --target-spacing 2 --min-samples 25 --max-samples 1024

Output columns (CSV): category, box sizes, exact/sampled IoU, errors, grid size, geometry params.

See oriented_det/ops/README.md for design rationale and benchmark tables (spacing 2 px, min 25, max 1024).

diagnose_coco_gap.py

CPU-only comparison of a COCO YOLO-OBB checkpoint with Ultralytics v8 small: pycocotools versus the in-train AP, one-image task-aligned assigner terms, letterbox pixels, and parameter count. Writes runs/coco_gap/report.json and runs/coco_gap/pixels.png. Set CUDA_VISIBLE_DEVICES="" so it stays off the GPU.

CUDA_VISIBLE_DEVICES="" python tools/diagnose_coco_gap.py

The epoch-60 numbers are in configs/yolo_obb/README.md.

diagnose_mosaic_gap.py

CPU-only mosaic comparison for the COCO YOLO-OBB recipe. The same four train photos go through this letterbox-then-mosaic path and through the Ultralytics v8 mosaic. Reports box long side and the fraction of the 640 canvas that is photo, letterbox black, or gray fill. Writes runs/coco_gap/mosaic_report.json, mosaic_matched.png, and mosaic_train.png.

CUDA_VISIBLE_DEVICES="" python tools/diagnose_mosaic_gap.py

Tips

  1. Preview augmentations: Run preview_augmentation.py on your config to verify flips, random rotate, and Albumentations before a long training run
  2. Test on small dataset: Before full training, test on a subset of your data
  3. Monitor training: Check checkpoint directory for saved models
  4. Adjust hyperparameters: Learning rate, batch size, and thresholds may need tuning for your data