jennyxue commited on
Commit
4d1aa89
·
verified ·
1 Parent(s): c5b6659

fp16 build of MobileSAM v2

Browse files
Files changed (3) hide show
  1. fp16/decoder.onnx +3 -0
  2. fp16/encoder.onnx +3 -0
  3. fp16/pipeline.py +89 -0
fp16/decoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d0602745ee8f93e8c57d9f660d824fbfec1cfd600b9ee8a060638e076feb266
3
+ size 16497093
fp16/encoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69e5ab89f4aa8b10350e147dc33f3b280b6dcac1c9791cf315b818ecf2c984a3
3
+ size 14073062
fp16/pipeline.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MobileSAM (the promptable segmenter of MobileSAM v2) with ONNX Runtime: the TinyViT image encoder and SAM's ONNX
2
+ decoder wrapper as graphs, numpy around them, following the repository's SamPredictor: the longest side resized to 1024
3
+ (Pillow bilinear), SAM's pixel mean / std, padded bottom-right to 1024 x 1024; prompt coordinates scaled the same way;
4
+ masks returned at the image size by the decoder (logits > 0). Multimask point prompts give masks 1-3, single-mask
5
+ (box) prompts mask 0, as SamPredictor does. Needs numpy, onnxruntime (or onnxruntime-gpu) and Pillow.
6
+
7
+ python fp16/pipeline.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1] [--cuda]
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ MEAN = np.array([123.675, 116.28, 103.53], np.float32)[:, None, None]
17
+ STD = np.array([58.395, 57.12, 57.375], np.float32)[:, None, None]
18
+
19
+
20
+ class MobileSAM:
21
+ def __init__(self, folder, provider="cpu"):
22
+ import onnxruntime as ort
23
+ folder = Path(folder)
24
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
25
+ try:
26
+ ort.preload_dlls()
27
+ except Exception:
28
+ pass
29
+ so = ort.SessionOptions()
30
+ so.log_severity_level = 3
31
+ pv = ["CPUExecutionProvider"] if provider == "cpu" else [
32
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"}), "CPUExecutionProvider"]
33
+ self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=pv) for n in ("encoder", "decoder")}
34
+
35
+ @staticmethod
36
+ def _scale(h, w, long=1024):
37
+ s = long / max(h, w)
38
+ return int(h * s + 0.5), int(w * s + 0.5)
39
+
40
+ def embed(self, rgb):
41
+ """rgb: H x W x 3 uint8 -> (embeddings, (H, W))."""
42
+ from PIL import Image
43
+ H, W = rgb.shape[:2]
44
+ nh, nw = self._scale(H, W)
45
+ x = np.asarray(Image.fromarray(rgb).resize((nw, nh), Image.BILINEAR), np.float32).transpose(2, 0, 1)
46
+ x = (x - MEAN) / STD
47
+ x = np.pad(x, ((0, 0), (0, 1024 - nh), (0, 1024 - nw)))[None].astype(np.float32)
48
+ return self.s["encoder"].run(None, {"image": x})[0], (H, W)
49
+
50
+ def _coords(self, xy, size):
51
+ H, W = size
52
+ nh, nw = self._scale(H, W)
53
+ return np.asarray(xy, np.float32) * np.array([nw / W, nh / H], np.float32)
54
+
55
+ def _run(self, emb, size, coords, labels):
56
+ out = self.s["decoder"].run(None, {
57
+ "image_embeddings": emb, "point_coords": coords[None].astype(np.float32),
58
+ "point_labels": np.asarray(labels, np.float32)[None], "mask_input": np.zeros((1, 1, 256, 256), np.float32),
59
+ "has_mask_input": np.zeros(1, np.float32), "orig_im_size": np.asarray(size, np.float32)})
60
+ return out[0][0] > 0, out[1][0]
61
+
62
+ def point(self, emb, size, points, labels=None):
63
+ """points [[x, y], ...] (label 1 foreground, 0 background) -> 3 masks [3, H, W] and their scores."""
64
+ lab = [1] * len(points) if labels is None else list(labels)
65
+ c = np.concatenate([self._coords(points, size), np.zeros((1, 2), np.float32)]) # + the padding point
66
+ m, s = self._run(emb, size, c, lab + [-1])
67
+ return m[1:], s[1:]
68
+
69
+ def box(self, emb, size, box):
70
+ m, s = self._run(emb, size, self._coords(np.asarray(box).reshape(2, 2), size), [2, 3])
71
+ return m[0], s[0]
72
+
73
+
74
+ if __name__ == "__main__":
75
+ import argparse
76
+ from PIL import Image
77
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
78
+ ap.add_argument("image"); ap.add_argument("output")
79
+ ap.add_argument("--point", type=float, nargs=2); ap.add_argument("--box", type=float, nargs=4)
80
+ ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)); ap.add_argument("--cuda", action="store_true")
81
+ a = ap.parse_args()
82
+ sam = MobileSAM(a.dir, "cuda" if a.cuda else "cpu")
83
+ emb, size = sam.embed(np.array(Image.open(a.image).convert("RGB")))
84
+ out = {}
85
+ if a.point:
86
+ out["point_masks"], out["point_scores"] = sam.point(emb, size, [a.point])
87
+ if a.box:
88
+ out["box_mask"], out["box_score"] = sam.box(emb, size, a.box)
89
+ np.savez_compressed(a.output, **out)