Web Analytics

no-time-to-train

⭐ 228 stars Italian by miquel-espinosa

🌐 Lingua

🚀 No Time to Train!

Segmentazione di istanza di riferimento senza addestramento

GitHub Website arXiv

Stato dell’arte (Papers with Code) _SOTA 1-shot_ | PWC-21CBCE?style=flat&logo=paperswithcode)

_SOTA 10-shot_ | PWC-21CBCE?style=flat&logo=paperswithcode)

_SOTA 30-shot_ | PWC-21CBCE?style=flat&logo=paperswithcode)


🚨 Aggiornamento (22 luglio 2025): Sono state aggiunte istruzioni per dataset personalizzati!
🔔 Aggiornamento (16 luglio 2025): Il codice è stato aggiornato con le istruzioni!


📋 Indice

🎯 Punti salienti

Link:

📜 Abstract

The performance of image segmentation models has historically been constrained by the high cost of collecting large-scale annotated data. The Segment Anything Model (SAM) alleviates this original problem through a promptable, semantics-agnostic, segmentation paradigm and yet still requires manual visual-prompts or complex domain-dependent prompt-generation rules to process a new image. Towards reducing this new burden, our work investigates the task of object segmentation when provided with, alternatively, only a small set of reference images. Our key insight is to leverage strong semantic priors, as learned by foundation models, to identify corresponding regions between a reference and a target image. We find that correspondences enable automatic generation of instance-level segmentation masks for downstream tasks and instantiate our ideas via a multi-stage, training-free method incorporating (1) memory bank construction; (2) representation aggregation and (3) semantic-aware feature matching. Our experiments show significant improvements on segmentation metrics, leading to state-of-the-art performance on COCO FSOD (36.8% nAP), PASCAL VOC Few-Shot (71.2% nAP50) and outperforming existing training-free approaches on the Cross-Domain FSOD benchmark (22.4% nAP).

cdfsod-results-final-comic-sans-min

🧠 Architecture

training-free-architecture-comic-sans-min

🛠️ Installation instructions

1. Clone the repository

git clone https://github.com/miquel-espinosa/no-time-to-train.git
cd no-time-to-train

2. Crea l'ambiente conda

Creeremo un ambiente conda con i pacchetti necessari.

conda env create -f environment.yml
conda activate no-time-to-train

3. Installa SAM2 e DinoV2

Installeremo SAM2 e DinoV2 dal sorgente.

pip install -e .
cd dinov2
pip install -e .
cd ..

4. Scarica i dataset

Per favore scarica il dataset COCO e posizionalo in data/coco

5. Scarica i checkpoint di SAM2 e DinoV2

Scaricheremo gli stessi checkpoint SAM2 utilizzati nell'articolo. (Tieni presente, tuttavia, che i checkpoint SAM2.1 sono già disponibili e potrebbero offrire prestazioni migliori.)

mkdir -p checkpoints/dinov2
cd checkpoints
wget https://dl.fbaipublicfiles.com/segment_anything_2/072824/sam2_hiera_large.pt
cd dinov2
wget https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth
cd ../..

📊 Codice di inferenza

⚠️ Disclaimer: Questo è codice di ricerca — aspettatevi un po' di caos!

Riproduzione dei risultati SOTA a 30-shot su Few-shot COCO

Definire variabili utili e creare una cartella per i risultati:

CONFIG=./no_time_to_train/new_exps/coco_fewshot_10shot_Sam2L.yaml
CLASS_SPLIT="few_shot_classes"
RESULTS_DIR=work_dirs/few_shot_results
SHOTS=30
SEED=33
GPUS=4

mkdir -p $RESULTS_DIR FILENAME=few_shot_${SHOTS}shot_seed${SEED}.pkl

#### 0. Crea set di riferimento

python no_time_to_train/dataset/few_shot_sampling.py \
        --n-shot $SHOTS \
        --out-path ${RESULTS_DIR}/${FILENAME} \
        --seed $SEED \
        --dataset $CLASS_SPLIT
#### 1. Riempire la memoria con riferimenti

python run_lightening.py test --config $CONFIG \
                              --model.test_mode fill_memory \
                              --out_path ${RESULTS_DIR}/memory.ckpt \
                              --model.init_args.model_cfg.memory_bank_cfg.length $SHOTS \
                              --model.init_args.dataset_cfgs.fill_memory.memory_pkl ${RESULTS_DIR}/${FILENAME} \
                              --model.init_args.dataset_cfgs.fill_memory.memory_length $SHOTS \
                              --model.init_args.dataset_cfgs.fill_memory.class_split $CLASS_SPLIT \
                              --trainer.logger.save_dir ${RESULTS_DIR}/ \
                              --trainer.devices $GPUS
#### 2. Post-elaborazione della memoria di banco

python run_lightening.py test --config $CONFIG \
                              --model.test_mode postprocess_memory \
                              --model.init_args.model_cfg.memory_bank_cfg.length $SHOTS \
                              --ckpt_path ${RESULTS_DIR}/memory.ckpt \
                              --out_path ${RESULTS_DIR}/memory_postprocessed.ckpt \
                              --trainer.devices 1
#### 3. Inferenza sulle immagini di destinazione

python run_lightening.py test --config $CONFIG  \
                              --ckpt_path ${RESULTS_DIR}/memory_postprocessed.ckpt \
                              --model.init_args.test_mode test \
                              --model.init_args.model_cfg.memory_bank_cfg.length $SHOTS \
                              --model.init_args.model_cfg.dataset_name $CLASS_SPLIT \
                              --model.init_args.dataset_cfgs.test.class_split $CLASS_SPLIT \
                              --trainer.logger.save_dir ${RESULTS_DIR}/ \
                              --trainer.devices $GPUS
Se desideri visualizzare i risultati dell'inferenza online (man mano che vengono calcolati), aggiungi l'argomento:

    --model.init_args.model_cfg.test.online_vis True
Per regolare il parametro di soglia del punteggio score_thr, aggiungere l'argomento (ad esempio, per visualizzare tutte le istanze con punteggio superiore a 0.4):
    --model.init_args.model_cfg.test.vis_thr 0.4
Le immagini verranno ora salvate in results_analysis/few_shot_classes/. L'immagine a sinistra mostra la ground truth, l'immagine a destra mostra le istanze segmentate trovate dal nostro metodo senza training.

Nota che in questo esempio stiamo usando lo split few_shot_classes, quindi dovremmo aspettarci di vedere solo le istanze segmentate delle classi presenti in questo split (non tutte le classi in COCO).

#### Risultati

Dopo aver elaborato tutte le immagini nel set di validazione, dovresti ottenere:

BBOX RESULTS:
  Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.368

SEGM RESULTS: Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.342


🔍 Dataset personalizzato

Forniamo le istruzioni per eseguire la nostra pipeline su un dataset personalizzato. Il formato delle annotazioni è sempre in formato COCO.

TLDR; Per vedere direttamente come eseguire la pipeline completa su dataset personalizzati, consulta scripts/matching_cdfsod_pipeline.sh insieme agli script di esempio dei dataset CD-FSOD (ad es. scripts/dior_fish.sh)

0. Prepara un dataset personalizzato ⛵🐦

Immaginiamo di voler rilevare barche⛵ e uccelli🐦 in un dataset personalizzato. Per utilizzare il nostro metodo avremo bisogno di:

Abbiamo preparato uno script di esempio per creare un dataset personalizzato con immagini COCO, per un'impostazione 1-shot.
mkdir -p data/my_custom_dataset
python scripts/make_custom_dataset.py
Questo creerà un dataset personalizzato con la seguente struttura di cartelle:
data/my_custom_dataset/
    ├── annotations/
    │   ├── custom_references.json
    │   ├── custom_targets.json
    │   └── references_visualisations/
    │       ├── bird_1.jpg
    │       └── boat_1.jpg
    └── images/
        ├── 429819.jpg
        ├── 101435.jpg
        └── (all target and reference images)
Visualizzazione delle immagini di riferimento (1-shot):

| Immagine di riferimento 1-shot per UCCELLO 🐦 | Immagine di riferimento 1-shot per BARCA ⛵ | |:--------------------------------------------:|:-------------------------------------------:| | bird_1 | boat_1 |

0.1 Se sono disponibili solo annotazioni bbox

Forniamo anche uno script per generare maschere di segmentazione a livello di istanza utilizzando SAM2. Questo è utile se sono disponibili solo annotazioni di bounding box per le immagini di riferimento.

# Download sam_h checkpoint. Feel free to use more recent checkpoints (note: code might need to be adapted)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth -O checkpoints/sam_vit_h_4b8939.pth

Run automatic instance segmentation from ground truth bounding boxes.

python no_time_to_train/dataset/sam_bbox_to_segm_batch.py \ --input_json data/my_custom_dataset/annotations/custom_references.json \ --image_dir data/my_custom_dataset/images \ --sam_checkpoint checkpoints/sam_vit_h_4b8939.pth \ --model_type vit_h \ --device cuda \ --batch_size 8 \ --visualize
Immagini di riferimento con maschere di segmentazione a livello di istanza (generate da SAM2 dai riquadri gt, 1-shot):

La visualizzazione delle maschere di segmentazione generate è salvata in data/my_custom_dataset/annotations/custom_references_with_SAM_segm/references_visualisations/.

| Immagine di riferimento 1-shot per UCCELLO 🐦 (segmentata automaticamente con SAM) | Immagine di riferimento 1-shot per BARCA ⛵ (segmentata automaticamente con SAM) | |:---------------------------------:|:----------------------------------:| | bird_1_with_SAM_segm | boat_1_with_SAM_segm |

0.2 Convertire annotazioni coco in file pickle

python no_time_to_train/dataset/coco_to_pkl.py \
    data/my_custom_dataset/annotations/custom_references_with_segm.json \
    data/my_custom_dataset/annotations/custom_references_with_segm.pkl \
    1

1. Riempire la memoria con riferimenti

Per prima cosa, definire le variabili utili e creare una cartella per i risultati. Per una corretta visualizzazione delle etichette, i nomi delle classi devono essere ordinati in base all'id della categoria come appare nel file json. Ad esempio, bird ha id categoria 16, boat ha id categoria 9. Quindi, CAT_NAMES=boat,bird.

DATASET_NAME=my_custom_dataset
DATASET_PATH=data/my_custom_dataset
CAT_NAMES=boat,bird
CATEGORY_NUM=2
SHOT=1
YAML_PATH=no_time_to_train/pl_configs/matching_cdfsod_template.yaml
PATH_TO_SAVE_CKPTS=./tmp_ckpts/my_custom_dataset
mkdir -p $PATH_TO_SAVE_CKPTS
Esegui il passaggio 1:

python run_lightening.py test --config $YAML_PATH \
    --model.test_mode fill_memory \
    --out_path $PATH_TO_SAVE_CKPTS/$DATASET_NAME\_$SHOT\_refs_memory.pth \
    --model.init_args.dataset_cfgs.fill_memory.root $DATASET_PATH/images \
    --model.init_args.dataset_cfgs.fill_memory.json_file $DATASET_PATH/annotations/custom_references_with_segm.json \
    --model.init_args.dataset_cfgs.fill_memory.memory_pkl $DATASET_PATH/annotations/custom_references_with_segm.pkl \
    --model.init_args.dataset_cfgs.fill_memory.memory_length $SHOT \
    --model.init_args.dataset_cfgs.fill_memory.cat_names $CAT_NAMES \
    --model.init_args.model_cfg.dataset_name $DATASET_NAME \
    --model.init_args.model_cfg.memory_bank_cfg.length $SHOT \
    --model.init_args.model_cfg.memory_bank_cfg.category_num $CATEGORY_NUM \
    --trainer.devices 1

2. Post-elaborazione della memoria di banco

python run_lightening.py test --config $YAML_PATH \
    --model.test_mode postprocess_memory \
    --ckpt_path $PATH_TO_SAVE_CKPTS/$DATASET_NAME\_$SHOT\_refs_memory.pth \
    --out_path $PATH_TO_SAVE_CKPTS/$DATASET_NAME\_$SHOT\_refs_memory_postprocessed.pth \
    --model.init_args.model_cfg.dataset_name $DATASET_NAME \
    --model.init_args.model_cfg.memory_bank_cfg.length $SHOT \
    --model.init_args.model_cfg.memory_bank_cfg.category_num $CATEGORY_NUM \
    --trainer.devices 1

3. Inferenza sulle immagini di destinazione

Se ONLINE_VIS è impostato su True, i risultati delle predizioni verranno salvati in results_analysis/my_custom_dataset/ e visualizzati man mano che vengono calcolati. NOTA che l'esecuzione con la visualizzazione online è molto più lenta.

Sentiti libero di modificare la soglia di punteggio VIS_THR per visualizzare più o meno istanze segmentate.

ONLINE_VIS=True
VIS_THR=0.4
python run_lightening.py test --config $YAML_PATH \
    --model.test_mode test \
    --ckpt_path $PATH_TO_SAVE_CKPTS/$DATASET_NAME\_$SHOT\_refs_memory_postprocessed.pth \
    --model.init_args.model_cfg.dataset_name $DATASET_NAME \
    --model.init_args.model_cfg.memory_bank_cfg.length $SHOT \
    --model.init_args.model_cfg.memory_bank_cfg.category_num $CATEGORY_NUM \
    --model.init_args.model_cfg.test.imgs_path $DATASET_PATH/images \
    --model.init_args.model_cfg.test.online_vis $ONLINE_VIS \
    --model.init_args.model_cfg.test.vis_thr $VIS_THR \
    --model.init_args.dataset_cfgs.test.root $DATASET_PATH/images \
    --model.init_args.dataset_cfgs.test.json_file $DATASET_PATH/annotations/custom_targets.json \
    --model.init_args.dataset_cfgs.test.cat_names $CAT_NAMES \
    --trainer.devices 1

Risultati

Le metriche di prestazione (con gli stessi parametri esatti dei comandi sopra) dovrebbero essere:

BBOX RESULTS:
  Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.478

SEGM RESULTS: Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.458

I risultati visivi sono salvati in results_analysis/my_custom_dataset/. Nota che il nostro metodo funziona per i falsi negativi, cioè immagini che non contengono istanze delle classi desiderate.

Clicca sulle immagini per ingrandirle ⬇️

| Immagine target con barche ⛵ (sinistra GT, destra predizioni) | Immagine target con uccelli 🐦 (sinistra GT, destra predizioni) | |:----------------------:|:----------------------:| | 000000459673 | 000000407180 |

| Immagine target con barche e uccelli ⛵🐦 (sinistra GT, destra predizioni) | Immagine target senza barche né uccelli 🚫 (sinistra GT, destra predizioni) | |:---------------------------------:|:----------------------------------:| | 000000517410 | 000000460598 |

📚 Citazione

Se utilizzi questo lavoro, per favore citaci:

@article{espinosa2025notimetotrain,
  title={No time to train! Training-Free Reference-Based Instance Segmentation},
  author={Miguel Espinosa and Chenhongyi Yang and Linus Ericsson and Steven McDonagh and Elliot J. Crowley},
  journal={arXiv preprint arXiv:2507.02798},
  year={2025},
  primaryclass={cs.CV}
}

--- Tranlated By Open Ai Tx | Last indexed: 2025-09-06 ---