Pierre Roy

AyfriMinecraft-Mobs-Vision

A multi-task Computer Vision model that classifies Minecraft mobs and predicts their on-screen bounding boxes from game screenshots.

Jupyter Notebook 0 stars 0 forks updated 25/06/2026

Minecraft Mob Vision

A multi-task Computer Vision model that classifies Minecraft mobs and predicts their on-screen bounding boxes from game screenshots. Built as a deep learning class project (object detection track - bonus points eligible).

Goal

Given a 512x288 screenshot of a Minecraft scene, the model outputs:

  • Classification: which of the 87 mob types is present
  • Bounding box: YOLO-normalized (cx, cy, w, h) on-screen position

Results

Headline numbers below are the honest ones: the test split is grouped by spawn (group_by_spawn = true), so no orbit frame of a spawn that the model trained on can leak into the test set. Current model is ConvNeXtV2-nano @ 256x448, evaluated on the held-out test split (3,922 images, 87 classes):

Metric Value
Top-1 accuracy 93.6%
Top-5 accuracy 98.2%
Mean IoU 86.8%

Headline metrics on the spawn-grouped test set

Why these are lower than you might have seen before: the generator orbits the camera around each fixed mob spawn, so successive frames are near-duplicates. A naive per-frame split (group_by_spawn = false) scatters those near-duplicates across train/test and inflates Top-1 to ~96%. The spawn-grouped split removes that leak and is the number to trust for real generalization.

Where errors concentrate (from the per-condition breakdown):

Bucket Weakest slice Acc
Bbox size Small boxes (area < 0.083) 83.9%
Distance Far mobs (7-79 blocks) 83.5%
Weather Rain 91.3%

Medium/large boxes and close/mid distances all sit at 96-98%. Residual misclassifications are semantically reasonable look-alikes: ghast vs happy_ghast, cod vs tadpole, horse/mule vs donkey, vindicator vs pillager, tropical_fish vs salmon. The hardest classes are small/near-invisible water mobs (cod, tadpole, tropical_fish, pufferfish) and the two ghast variants.

Predictions on real web screenshots (class + confidence + bbox), well outside the synthetic training distribution:

Predictions on real web screenshots

Why ConvNeXtV2-nano over the lighter MobileNetV4 backbones (used earlier for fast iteration): much sharper saliency (precise, localized attention) and better generalization to real web screenshots (data/test_input). Earlier MobileNetV4-small iterations (see data/history) used classic Grad-CAM and produced large diffuse heatmaps, whereas the current grad×input attribution is small and precise.

Grad×input saliency: attention lands on the mob, not the backdrop

See notebook.ipynb for the full methodology, plots and error analysis, and presentation/ for the slides.

Dataset

Generated by Minecraft-Images-Mobs-Generator, a Fabric mod that automates screenshot capture with ground-truth labels computed via 3D projection math (no manual annotation).

Property Value
Frames 26,010 frames (87 mob classes, ~299 frames/class avg, range 205-573) - well balanced (~2.8x imbalance)
Resolution 512x288 px (.jpg)
Classes 87 Minecraft mob types
Format YOLO-normalized bounding box per frame (one box/frame; multi-box detection is future work)
Distance 1.0-83.7 blocks from camera

Diversity per mob: 3 weather conditions (clear / rain / thunder) x full 24h lighting cycle x multiple biomes x orbital camera angles.

Sample frames with ground-truth boxes

Data files

File Description
data/images/ JPG frames - frame_XXXXXX.jpg
data/frames.csv Mob metadata: frame, mob, weather, time_ticks, shot, mob_idx, mob_x/y/z, negative
data/boxes.csv Bounding boxes: frame, class_id, cx, cy, w, h, dist_blocks
data/test_input/ Real web screenshots for out-of-distribution sanity checks
data/test_output/ Annotated predictions written by scripts.predict_batch

Join key between both CSVs is frame. Bounding boxes are YOLO-normalized (cx, cy, w, h) in [0, 1]. Rows with negative = 1 (no mob in frame) are filtered out at load.

Model Architecture

MobDetector - configurable timm backbone + two heads. Current best uses ConvNeXtV2-nano at 256x448; the lighter MobileNetV4-small (224x384) is the shipped default for fast iteration on low VRAM.

Input (3, H, W)   # default 224x384, best model 256x448
  -> timm backbone (num_classes=0, global_pool="" -> raw feature map for saliency)
  -> feature map (B, C, H', W')
        +- AdaptiveAvgPool2d(1) -> Flatten -> Dropout -> Linear -> (num_classes,)   # cls_logits
        +- Conv2d(C->256,1x1) -> ReLU -> AdaptiveAvgPool2d(4) -> Flatten
             -> Linear(4096,256) -> ReLU -> Linear(256,4) -> Sigmoid -> (4,)  # bbox

Backbone is swappable via config.toml (model.backbone, model.img_size) - no code changes needed. Full model is ~16.3 M params with the ConvNeXtV2-nano backbone.

Loss: CrossEntropy(label_smoothing=0.1) + bbox_weight * CIoU

Training: AdamW + warmup (backbone frozen for warmup_epochs) + CosineAnnealingLR + AMP + torch.compile (Triton backend) + channels_last + early stopping on 0.7*acc + 0.3*iou.

Images are pre-processed once into a disk-backed memmap cache (data/cache/) - EqualizeV + resize applied at cache build time, not every epoch.

Stack

Tool Version
Python 3.13
PyTorch 2.12.0+cu130
torchvision 0.27.0+cu130
timm 1.0.27
pandas 3.0.3
Pillow 12.2.0
numpy 2.4.6
Package manager uv

GPU target: RTX 4060 Ti (16 GB VRAM), CUDA 13.0. Also runs on 6 GB VRAM (set batch_size = 32 in config.toml).

Setup

uv sync

config.toml is created automatically with default values on the first run.

Commands

# Train (saves checkpoints/best.pth + last.pth)
uv run -m scripts.train

# Evaluate on test split (top-1/5 acc, mean IoU, per-class acc+IoU, confusion matrix,
# weather / time-of-day / bbox-size / distance breakdowns)
uv run -m scripts.evaluate

# Run inference on a single image (saves image_pred.png with bbox + label)
uv run -m scripts.predict path/to/image.png

# Show top-5 predictions instead of default top-3, and overlay a saliency heatmap
uv run -m scripts.predict path/to/image.png --top 5 --heatmap

# Use a specific checkpoint
uv run -m scripts.predict path/to/image.png --checkpoint checkpoints/last.pth

# Batch inference over a folder (defaults: data/test_input -> data/test_output)
uv run -m scripts.predict_batch --heatmap

# Live screen-capture overlay that labels mobs in real time (Windows)
uv run -m scripts.live_overlay            # transparent click-through overlay
uv run -m scripts.live_overlay --mirror   # mirror window (better for screen-sharing)

# Debug label ordering and dataset stats (add --gpu for CUDA benchmarks)
uv run -m scripts.debug_labels
uv run -m scripts.debug_labels --gpu

# Type check
uv run pyrefly check --output-format=min-text --summary=none

# Lint / format
uvx ruff check .
uvx ruff format .

Configuration

All tuneable knobs live in config.toml (gitignored, auto-generated from defaults on first run). Edit it without touching any Python.

[augmentation]

Key Default Why
color_jitter_brightness 0.2 Simulates Minecraft's variable torch and ambient sky lighting across biomes.
color_jitter_contrast 0.2 Robustness to screen gamma and shadow differences across biomes.
color_jitter_hue 0.05 Small hue shift handles texture pack color drift without distorting mob identity.
color_jitter_saturation 0.2 Covers desaturated biomes (snowy) vs vivid ones (jungle).
equalize_v true Equalises the HSV Value channel before caching to remove the 24h lighting cycle bias, which is deterministic noise unrelated to mob identity. Applied once at cache build time.
hflip_prob 0.5 Horizontal flip doubles effective dataset size; mob textures are bilaterally symmetric. The bbox cx is mirrored to match.
posterize_bits 4 Reduces color quantization noise from compression artifacts in captured frames. Set to 0 to disable. Valid range: 1-8.

[data]

Key Default Why
ckpt_dir "checkpoints" Output directory for best.pth and last.pth.
data_dir "data" Root of the dataset: images/, frames.csv, boxes.csv.
group_by_spawn false When true, splits by spawn block (class_id, mob_x/y/z) so no near-duplicate orbit frame leaks across train/test. Recommended for honest metrics; uses all frames and ignores images_per_class.
image_ext "jpg" Must match the imageFormat setting in the Kotlin mod.
images_per_class 0 Cap of frames sampled per class before splitting (0 = use all). Speeds up iteration on the full 26k-frame set. Ignored when group_by_spawn = true.
seed 42 Controls the train/val/test split shuffle. Change to test split stability across seeds.
train_ratio 0.70 70/15/15 split. Increase if val performance is noisy due to small dataset size.
val_ratio 0.15 The test split is 1 - train_ratio - val_ratio.

[model]

Key Default Why
backbone "mobilenetv4_conv_small.e2400_r224_in1k" Any timm backbone that accepts pretrained=True. Swapping this is the fastest way to trade accuracy for speed. The current best run uses "convnextv2_nano.fcmae_ft_in1k" (16.3 M total); alternatives include "mobilenetv4_conv_medium.e500_r224_in1k" (8.4 M backbone) or "efficientnet_b0.ra_in1k".
dropout 0.3 Applied before the classification head only. Higher values help when the backbone is large relative to dataset size.
img_size [224, 384] [H, W] fed to the network. Rectangular to preserve the 16:9 source ratio. Must be divisible by 32. Larger sizes improve small-mob accuracy at the cost of VRAM and speed.

[training]

Key Default Why
backbone_lr_mul 0.1 Backbone LR = lr * backbone_lr_mul after warmup. Low multiplier prevents destroying pretrained weights while still allowing fine-tuning.
batch_size 64 Reduce to 32 or 48 if OOM. Larger batches stabilize the bbox regression loss.
bbox_weight 1.0 Weight of CIoU in the total loss. CIoU is in [0, ~2], well-balanced with cross-entropy at 1.0.
epochs 50 Upper bound; early stopping (patience) usually triggers before this.
label_smoothing 0.1 Prevents the classifier from becoming overconfident on visually ambiguous mobs (e.g. zombie vs drowned).
lr 1e-3 Peak LR for head parameters; backbone uses lr * backbone_lr_mul. Decays via CosineAnnealingLR.
num_workers 4 Train DataLoader workers. Validation runs single-threaded (num_workers=0) to dodge Windows spawn overhead.
patience 8 Early-stop after this many epochs without improvement in 0.7*acc + 0.3*iou.
prefetch_factor 2 Batches prefetched per worker. Raise to 4+ if the GPU is starving waiting for data.
warmup_epochs 3 Epochs with backbone frozen, so randomly-initialised heads can converge before the pretrained weights are touched.
weight_decay 1e-4 L2 regularisation via AdamW.

Project Structure

checkpoints/      # saved weights (gitignored)
config.toml       # local experiment config (gitignored, auto-generated)
data/
  boxes.csv
  frames.csv
  cache/          # uint8 memmap of pre-processed frames (gitignored)
  images/         # JPG frames (gitignored)
  history/        # saved debug/saliency images from past runs
  test_input/     # real web screenshots for OOD checks
  test_output/    # annotated batch-inference results
presentation/
  assets/         # images used in slides
  index.html      # slides (French)
scripts/
  evaluate.py       # test-set evaluation (top-1/5 acc, IoU, per-class + condition breakdowns)
  live_overlay.py   # real-time screen-capture mob labelling overlay (Windows)
  predict.py        # single-image inference with optional saliency heatmap
  predict_batch.py  # folder inference -> annotated output folder
  train.py          # training loop
src/
  config.py       # loads config.toml into frozen dataclasses at import time
  dataset.py      # MobDataset + make_splits (per-frame or spawn-grouped)
  metrics.py      # bbox_iou, ciou_loss
  model.py        # MobDetector (timm backbone, configurable)
  transforms.py   # static (cache-time) + runtime image pipelines
notebook.ipynb    # full methodology, plots, error analysis