File size: 4,193 Bytes
53a8cb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
"""EfficientViT-SAM L2 with ONNX Runtime: the EfficientViT-L2 image encoder and SAM's ONNX decoder wrapper as graphs,
numpy around them, following the repository's EfficientViTSamPredictor: the longest side resized to 512 (Pillow
bilinear), SAM's pixel mean / std, padded bottom-right to 512 x 512; prompt coordinates in the 1024 frame;
masks returned at the image size by the decoder (logits > 0). Multimask point prompts give masks 1-3, single-mask
(box) prompts mask 0, as SamPredictor does. Needs numpy, onnxruntime (or onnxruntime-gpu) and Pillow.

    python fp16/pipeline.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1] [--cuda]
"""

from __future__ import annotations

from pathlib import Path

import numpy as np

MEAN = np.array([123.675, 116.28, 103.53], np.float32)[:, None, None]
STD = np.array([58.395, 57.12, 57.375], np.float32)[:, None, None]


class EfficientViTSAM:
    def __init__(self, folder, provider="cpu"):
        import onnxruntime as ort
        folder = Path(folder)
        if provider != "cpu" and hasattr(ort, "preload_dlls"):
            try:
                ort.preload_dlls()
            except Exception:
                pass
        so = ort.SessionOptions()
        so.log_severity_level = 3
        pv = ["CPUExecutionProvider"] if provider == "cpu" else [
            ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}), "CPUExecutionProvider"]
        self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=pv) for n in ("encoder", "decoder")}

    @staticmethod
    def _scale(h, w, long=1024):
        s = long / max(h, w)
        return int(h * s + 0.5), int(w * s + 0.5)

    def embed(self, rgb):
        """rgb: H x W x 3 uint8 -> (embeddings, (H, W))."""
        from PIL import Image
        H, W = rgb.shape[:2]
        nh, nw = self._scale(H, W, 512)
        x = np.asarray(Image.fromarray(rgb).resize((nw, nh), Image.BILINEAR), np.float32).transpose(2, 0, 1)
        x = (x - MEAN) / STD
        x = np.pad(x, ((0, 0), (0, 512 - nh), (0, 512 - nw)))[None].astype(np.float32)
        return self.s["encoder"].run(None, {"image": x})[0], (H, W)

    def _coords(self, xy, size):
        H, W = size
        nh, nw = self._scale(H, W)
        return np.asarray(xy, np.float32) * np.array([nw / W, nh / H], np.float32)

    def _run(self, emb, size, coords, labels):
        out = self.s["decoder"].run(None, {
            "image_embeddings": emb, "point_coords": coords[None].astype(np.float32),
            "point_labels": np.asarray(labels, np.float32)[None], "mask_input": np.zeros((1, 1, 256, 256), np.float32),
            "has_mask_input": np.zeros(1, np.float32), "orig_im_size": np.asarray(size, np.float32)})
        return out[0][0] > 0, out[1][0]

    def point(self, emb, size, points, labels=None):
        """points [[x, y], ...] (label 1 foreground, 0 background) -> 3 masks [3, H, W] and their scores."""
        lab = [1] * len(points) if labels is None else list(labels)
        c = np.concatenate([self._coords(points, size), np.zeros((1, 2), np.float32)])   # + the padding point
        m, s = self._run(emb, size, c, lab + [-1])
        return m[1:], s[1:]

    def box(self, emb, size, box):
        m, s = self._run(emb, size, self._coords(np.asarray(box).reshape(2, 2), size), [2, 3])
        return m[0], s[0]


if __name__ == "__main__":
    import argparse
    from PIL import Image
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("image"); ap.add_argument("output")
    ap.add_argument("--point", type=float, nargs=2); ap.add_argument("--box", type=float, nargs=4)
    ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)); ap.add_argument("--cuda", action="store_true")
    a = ap.parse_args()
    sam = EfficientViTSAM(a.dir, "cuda" if a.cuda else "cpu")
    emb, size = sam.embed(np.array(Image.open(a.image).convert("RGB")))
    out = {}
    if a.point:
        out["point_masks"], out["point_scores"] = sam.point(emb, size, [a.point])
    if a.box:
        out["box_mask"], out["box_score"] = sam.box(emb, size, a.box)
    np.savez_compressed(a.output, **out)