tinydepth-robot / inference.py
Zaidoppa's picture
Upload folder using huggingface_hub
31d2102 verified
Raw History Blame Contribute Delete
2.02 kB
"""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)