File size: 3,139 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import torch
import torch.nn.functional as F

HF_MODEL = 'nvidia/segformer-b5-finetuned-cityscapes-1024-1024'
HF_REVISION = '2c6f153e4c23c229e2fa2b188eb250607e030cd8'
SKY_LABEL = 10

semantic_classes = [
    'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
    'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
    'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
    'bicycle'
]

IMG_SCALE = (2048, 1024)
CROP = (1024, 1024)
STRIDE = (768, 768)
MEAN = torch.tensor([123.675, 116.28, 103.53]).view(1, 3, 1, 1)
STD = torch.tensor([58.395, 57.12, 57.375]).view(1, 3, 1, 1)


def load_segformer(path_or_id=HF_MODEL, revision=HF_REVISION):
    from transformers import SegformerForSemanticSegmentation
    seg, info = SegformerForSemanticSegmentation.from_pretrained(
        path_or_id, revision=None if path_or_id != HF_MODEL else revision, output_loading_info=True)
    if any(info[k] for k in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs')):
        raise SystemExit(f'SegFormer loading info {info}')
    seg = seg.cuda().eval().float()
    check_labels(seg)
    return seg


def check_labels(model):
    id2label = model.config.id2label
    got = [id2label[i] for i in range(len(semantic_classes))]
    if got != semantic_classes:
        raise RuntimeError(
            f"label order mismatch -- masks would be wrong.\n"
            f"  expected: {semantic_classes}\n  got:      {got}")


def _resize_keep_ratio(img):
    h, w = img.shape[:2]
    long_edge, short_edge = max(IMG_SCALE), min(IMG_SCALE)
    scale = min(long_edge / max(h, w), short_edge / min(h, w))
    return int(w * scale + 0.5), int(h * scale + 0.5)


@torch.no_grad()
def slide_inference(model, img_bgr, device, dtype):
    orig_h, orig_w = img_bgr.shape[:2]
    new_w, new_h = _resize_keep_ratio(img_bgr)

    x = torch.from_numpy(img_bgr[..., ::-1].copy()).permute(2, 0, 1)[None].float()
    x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", align_corners=False)
    x = ((x - MEAN) / STD).to(device=device, dtype=dtype)

    n_cls = model.config.num_labels
    logits = torch.zeros((1, n_cls, new_h, new_w), device=device, dtype=torch.float32)
    count = torch.zeros((1, 1, new_h, new_w), device=device, dtype=torch.float32)

    ch, cw = CROP
    sh, sw = STRIDE
    n_rows = max(new_h - ch + sh - 1, 0) // sh + 1
    n_cols = max(new_w - cw + sw - 1, 0) // sw + 1
    for r in range(n_rows):
        for c in range(n_cols):
            y2 = min(r * sh + ch, new_h); x2 = min(c * sw + cw, new_w)
            y1 = max(y2 - ch, 0);         x1 = max(x2 - cw, 0)
            crop = x[:, :, y1:y2, x1:x2]
            out = model(pixel_values=crop).logits
            out = F.interpolate(out.float(), size=crop.shape[2:],
                                mode="bilinear", align_corners=False)
            logits[:, :, y1:y2, x1:x2] += out
            count[:, :, y1:y2, x1:x2] += 1

    logits = logits / count
    logits = F.interpolate(logits, size=(orig_h, orig_w),
                           mode="bilinear", align_corners=False)
    return logits.argmax(dim=1)[0].to(torch.uint8).cpu().numpy()