File size: 2,015 Bytes
31d2102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run TinyDepth on an image or webcam.

    python inference.py image.jpg            # writes image_depth.png
    python inference.py --webcam             # live view (q to quit)
    python inference.py image.jpg --onnx     # use ONNX Runtime (no torch needed beyond this script)
"""
import sys
import cv2
import numpy as np

MEAN = np.array([0.485, 0.456, 0.406], np.float32)
STD = np.array([0.229, 0.224, 0.225], np.float32)
W, H = 320, 240


def load(use_onnx):
    if use_onnx:
        import onnxruntime as ort
        sess = ort.InferenceSession("tinydepth.onnx", providers=["CPUExecutionProvider"])
        return lambda x: sess.run(None, {"image": x})[0][0]
    import torch
    from safetensors.torch import load_file
    from model import TinyDepth
    m = TinyDepth(pretrained=False)
    m.load_state_dict(load_file("model.safetensors"))
    m.eval()
    return lambda x: m(torch.from_numpy(x)).detach().numpy()[0]


def predict(fn, bgr):
    rgb = cv2.cvtColor(cv2.resize(bgr, (W, H), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2RGB)
    x = ((rgb.astype(np.float32) / 255 - MEAN) / STD).transpose(2, 0, 1)[None]
    disp = fn(np.ascontiguousarray(x))  # relative inverse depth: larger = closer
    disp = cv2.resize(disp, (bgr.shape[1], bgr.shape[0]))
    vis = cv2.applyColorMap(cv2.normalize(disp, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8), cv2.COLORMAP_INFERNO)
    return disp, vis


if __name__ == "__main__":
    fn = load("--onnx" in sys.argv)
    if "--webcam" in sys.argv:
        cap = cv2.VideoCapture(0)
        while True:
            ok, frame = cap.read()
            if not ok: break
            _, vis = predict(fn, frame)
            cv2.imshow("TinyDepth", np.hstack([frame, vis]))
            if cv2.waitKey(1) & 0xFF == ord("q"): break
    else:
        path = [a for a in sys.argv[1:] if not a.startswith("--")][0]
        _, vis = predict(fn, cv2.imread(path))
        out = path.rsplit(".", 1)[0] + "_depth.png"
        cv2.imwrite(out, vis)
        print("wrote", out)