"""MobileSAM (the promptable segmenter of MobileSAM v2) with TensorRT engines: the same pipeline as pipeline.py (the repository's SamPredictor: longest side to 1024, SAM's mean / std, padded to 1024 x 1024; multimask point prompts give masks 1-3, box prompts mask 0), with - encoder.engine: image [1, 3, 1024, 1024] -> image_embeddings [1, 256, 64, 64]; - decoder.engine: SAM's ONNX decoder wrapper up to its low-resolution masks (image_embeddings, point_coords [1, N, 2], N 1-10, point_labels, mask_input, has_mask_input -> iou_predictions, low_res_masks [1, 4, 256, 256]). The wrapper's last step, resizing to the picture (SamOnnxModel.mask_postprocessing), needs the picture size as a shape tensor, which TensorRT can't take as a float input, so it is done here (OpenCV or numpy) with the same bilinear arithmetic. Needs numpy, Pillow, tensorrt-cu12 / tensorrt-lean-cu12 10.x and polygraphy; opencv-python makes the mask resize fast. python fp16/pipeline_trt.py photo.jpg masks.npz --point 410 300 [--box x0 y0 x1 y1] """ from __future__ import annotations import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from pipeline import MobileSAM # noqa: E402 from trt_runner import OrtLike # noqa: E402 def resize_bilinear(x, oh, ow): """torch.nn.functional.interpolate(x, (oh, ow), mode="bilinear", align_corners=False) for x [..., H, W]: OpenCV's INTER_LINEAR (the same half-pixel sampling, no antialiasing) when it is installed, else numpy.""" try: import cv2 flat = x.reshape(-1, *x.shape[-2:]) out = np.stack([cv2.resize(m, (ow, oh), interpolation=cv2.INTER_LINEAR) for m in flat]) return out.reshape(*x.shape[:-2], oh, ow) except ImportError: pass def axis(n_in, n_out): s = (np.arange(n_out, dtype=np.float64) + 0.5) * (n_in / n_out) - 0.5 s = np.maximum(s, 0) i0 = np.minimum(np.floor(s).astype(np.int64), n_in - 1) i1 = np.minimum(i0 + 1, n_in - 1) w = (s - i0).astype(np.float32) return i0, i1, w h, w = x.shape[-2:] r0, r1, wr = axis(h, oh) c0, c1, wc = axis(w, ow) y = x[..., r0, :] * (1 - wr)[:, None] + x[..., r1, :] * wr[:, None] return y[..., c0] * (1 - wc) + y[..., c1] * wc class MobileSAMTrt(MobileSAM): def __init__(self, folder=HERE): folder = Path(folder) self.s = {"encoder": OrtLike(folder / "encoder.engine", ["image_embeddings"]), "decoder": OrtLike(folder / "decoder.engine", ["iou_predictions", "low_res_masks"])} def _run(self, emb, size, coords, labels): iou, low = 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)}) H, W = size nh, nw = self._scale(H, W) m = resize_bilinear(low.astype(np.float32), 1024, 1024)[..., :nh, :nw] m = resize_bilinear(m, H, W) return m[0] > 0, iou[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) a = ap.parse_args() p = MobileSAMTrt() rgb = np.asarray(Image.open(a.image).convert("RGB")) emb, size = p.embed(rgb) out = {} if a.point: out["point_masks"], out["point_scores"] = p.point(emb, size, [a.point]) if a.box: out["box_mask"], out["box_score"] = p.box(emb, size, a.box) np.savez_compressed(a.output, **out) print({k: v.shape for k, v in out.items()})