File size: 3,939 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
"""EfficientViT-SAM (L0) with TensorRT engines: the same pipeline as pipeline.py (the repository's
EfficientViTSamPredictor: longest side to 512, SAM's mean / std, padded to 512 x 512, prompts in the 1024 frame;
multimask point prompts give masks 1-3, box prompts mask 0), with
- encoder.engine: image [1, 3, 512, 512] -> 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 fp32/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 EfficientViTSAM  # 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 EfficientViTSAMTrt(EfficientViTSAM):
    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 = EfficientViTSAMTrt()
    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()})