Views
No views yet
run_instance_segmentation.py.
The script uses the 🤗 Trainer API to manage training automatically, including distributed environments.
Here, we fine-tune a Mask2Former model on a subsample of the ADE20K dataset. We created a small dataset with approximately 2,000 images containing only "person" and "car" annotations; all other pixels are marked as "background."label2id mapping for this model:1label2id = {
2 "person": 0,
3 "car": 1,
4}1python run_instance_segmentation.py \
2 --model_name_or_path facebook/mask2former-swin-tiny-coco-instance \
3 --output_dir finetune-instance-segmentation-ade20k-mini-mask2former \
4 --dataset_name qubvel-hf/ade20k-mini \
5 --do_reduce_labels \
6 --image_height 256 \
7 --image_width 256 \
8 --do_train \
9 --fp16 \
10 --num_train_epochs 40 \
11 --learning_rate 1e-5 \
12 --lr_scheduler_type constant \
13 --per_device_train_batch_size 8 \
14 --gradient_accumulation_steps 2 \
15 --dataloader_num_workers 8 \
16 --dataloader_persistent_workers \
17 --dataloader_prefetch_factor 4 \
18 --do_eval \
19 --evaluation_strategy epoch \
20 --logging_strategy epoch \
21 --save_strategy epoch \
22 --save_total_limit 2 \
23 --push_to_hub1import torch
2import requests
3import matplotlib.pyplot as plt
4
5from PIL import Image
6from transformers import Mask2FormerForUniversalSegmentation, Mask2FormerImageProcessor
7
8# Load image
9image = Image.open(requests.get("http://farm4.staticflickr.com/3017/3071497290_31f0393363_z.jpg", stream=True).raw)
10
11# Load model and image processor
12device = "cuda"
13checkpoint = "qubvel-hf/finetune-instance-segmentation-ade20k-mini-mask2former"
14
15model = Mask2FormerForUniversalSegmentation.from_pretrained(checkpoint, device_map=device)
16image_processor = Mask2FormerImageProcessor.from_pretrained(checkpoint)
17
18# Run inference on image
19inputs = image_processor(images=[image], return_tensors="pt").to(device)
20with torch.no_grad():
21 outputs = model(**inputs)
22
23# Post-process outputs
24outputs = image_processor.post_process_instance_segmentation(outputs, target_sizes=[image.size[::-1]])
25
26print("Mask shape: ", outputs[0]["segmentation"].shape)
27print("Mask values: ", outputs[0]["segmentation"].unique())
28for segment in outputs[0]["segments_info"]:
29 print("Segment: ", segment)Mask shape: torch.Size([427, 640])
Mask values: tensor([-1., 0., 1., 2., 3., 4., 5., 6.])
Segment: {'id': 0, 'label_id': 0, 'was_fused': False, 'score': 0.946127}
Segment: {'id': 1, 'label_id': 1, 'was_fused': False, 'score': 0.961582}
Segment: {'id': 2, 'label_id': 1, 'was_fused': False, 'score': 0.968367}
Segment: {'id': 3, 'label_id': 1, 'was_fused': False, 'score': 0.819527}
Segment: {'id': 4, 'label_id': 1, 'was_fused': False, 'score': 0.655761}
Segment: {'id': 5, 'label_id': 1, 'was_fused': False, 'score': 0.531299}
Segment: {'id': 6, 'label_id': 1, 'was_fused': False, 'score': 0.929477}1import numpy as np
2import matplotlib.pyplot as plt
3
4segmentation = outputs[0]["segmentation"].numpy()
5
6plt.figure(figsize=(10, 10))
7plt.subplot(1, 2, 1)
8plt.imshow(np.array(image))
9plt.axis("off")
10plt.subplot(1, 2, 2)
11plt.imshow(segmentation)
12plt.axis("off")
13plt.show()