Views
No views yet
void, flat, construction, object, nature, sky, human, vehicle.sernet_model.pt1from torchvision.models.segmentation import DeepLabV3_ResNet101_Weights
2
3weights = DeepLabV3_ResNet101_Weights.DEFAULT
4preprocess = weights.transforms() # PIL -> Tensor + normalisation ImageNetpreprocess, p.ex. (H, W) = (480, 960).(B, 8, H, W) → argmax(dim=1) donne un masque (H, W) d’IDs de classe.1from huggingface_hub import hf_hub_download
2from torchvision.models.segmentation import DeepLabV3_ResNet101_Weights
3from PIL import Image
4import torch, numpy as np
5
6REPO_ID = "<votre-user>/p9-cityscapes-model"
7FILENAME = "sernet_model.pt"
8
9# 1) Charger le modèle TorchScript
10path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME) # cache auto (~/.cache/huggingface)
11model = torch.jit.load(path, map_location="cpu").eval()
12
13# 2) Préprocess (torchvision)
14weights = DeepLabV3_ResNet101_Weights.DEFAULT
15preprocess = weights.transforms()
16
17# 3) Préparer l’image
18Resample = getattr(Image, "Resampling", Image) # compat Pillow<9.1
19img = Image.open("demo.jpg").convert("RGB")
20img = img.resize((960, 480), Resample.BILINEAR) # optionnel (latence CPU)
21x = preprocess(img).unsqueeze(0) # [1,C,H,W]
22
23# 4) Prédire
24with torch.inference_mode():
25 out = model(x)
26
27logits = out["out"] if isinstance(out, dict) else out # (1,8,H,W)
28seg = torch.argmax(logits, 1).squeeze(0).cpu().numpy().astype("uint8")
29print("mask:", seg.shape, "classes:", np.unique(seg))1import numpy as np
2from matplotlib import colors
3
4PALETTE = ['b','g','r','c','m','y','k','w'] # 0..7
5
6def colorize(seg: np.ndarray) -> np.ndarray:
7 h, w = seg.shape
8 out = np.zeros((h, w, 3), dtype=np.float32)
9 for cid in range(8):
10 mask = (seg == cid)
11 r, g, b = colors.to_rgb(PALETTE[cid])
12 out[mask, 0] = r; out[mask, 1] = g; out[mask, 2] = b
13 return (out * 255).astype(np.uint8)960×480 pour une latence raisonnable.