fp32 build of EfficientViT-SAM
Browse files- .gitattributes +2 -0
- fp32/decoder.onnx +3 -0
- fp32/decoder.onnx.data +3 -0
- fp32/encoder.onnx +3 -0
- fp32/encoder.onnx.data +3 -0
- fp32/pipeline.py +89 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
fp32/decoder.onnx.data filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
fp32/encoder.onnx.data filter=lfs diff=lfs merge=lfs -text
|
fp32/decoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:72ff3fdc36d9c1ca4b5b75d8c83dc85306def496808cb6be28d58f1f410aa4f2
|
| 3 |
+
size 253735
|
fp32/decoder.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:df2017f2c3fc1a040d04742f5e1c1616165de9ac46eda09718cfe7a0cc4f04bf
|
| 3 |
+
size 16249856
|
fp32/encoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:35d5b72c6f743d6791419a31eae188c4c9a358f3f1fe47a1b22ab706cd418046
|
| 3 |
+
size 413779
|
fp32/encoder.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f5552293e854452738b86d24653c7d32b95fa746a45cc57de04af43994aa3fa9
|
| 3 |
+
size 228966784
|
fp32/pipeline.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EfficientViT-SAM L2 with ONNX Runtime: the EfficientViT-L2 image encoder and SAM's ONNX decoder wrapper as graphs,
|
| 2 |
+
numpy around them, following the repository's EfficientViTSamPredictor: the longest side resized to 512 (Pillow
|
| 3 |
+
bilinear), SAM's pixel mean / std, padded bottom-right to 512 x 512; prompt coordinates in the 1024 frame;
|
| 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 EfficientViTSAM:
|
| 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, 512)
|
| 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, 512 - nh), (0, 512 - 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 = EfficientViTSAM(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)
|