Zaidoppa commited on
Commit
31d2102
·
verified ·
1 Parent(s): c389340

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. README.md +55 -0
  3. demo.jpg +3 -0
  4. inference.py +54 -0
  5. model.py +44 -0
  6. model.safetensors +3 -0
  7. tinydepth.onnx +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ demo.jpg filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: pytorch
4
+ pipeline_tag: depth-estimation
5
+ tags: [depth-estimation, monocular-depth, robotics, edge, distillation, mobilenetv4, onnx]
6
+ datasets: [ahd03/diode-depth-3k]
7
+ base_model: depth-anything/Depth-Anything-V2-Small-hf
8
+ ---
9
+
10
+ # TinyDepth-Robot (1.36M params)
11
+
12
+ A tiny monocular **relative depth** model for robots and edge devices. It was distilled from
13
+ [Depth-Anything-V2-Small](https://huggingface.co/depth-anything/Depth-Anything-V2-Small-hf) (24.8M params)
14
+ into a **1.36M-parameter** MobileNetV4-Small encoder with a depthwise-separable FPN decoder,
15
+ which makes it about 18× smaller than the teacher. Training was done entirely on CPU.
16
+
17
+ ![demo](demo.jpg)
18
+ *Left to right: RGB, teacher (Depth-Anything-V2-Small), TinyDepth.*
19
+
20
+ ## Output
21
+ `disparity` (B, H, W): **relative inverse depth**, where larger values are closer. The values have no
22
+ scale. For metric depth, fit a scale and shift per scene (for example from a known floor plane or a
23
+ few lidar points), or use the map directly for obstacle and free-space reasoning.
24
+
25
+ ## Usage
26
+ ```bash
27
+ pip install torch timm safetensors opencv-python # or just onnxruntime opencv-python for --onnx
28
+ python inference.py image.jpg # -> image_depth.png
29
+ python inference.py image.jpg --onnx
30
+ python inference.py --webcam
31
+ ```
32
+ Input: RGB, ImageNet-normalized, default 320x240 (H and W should be multiples of 32).
33
+
34
+ ## Results (DIODE val, n=167, scale and shift aligned to ground truth)
35
+ | Model | Params | AbsRel ↓ | δ1 ↑ |
36
+ |---|---|---|---|
37
+ | Depth-Anything-V2-Small (teacher) | 24.8M | 0.213 | 0.736 |
38
+ | **TinyDepth-Robot** | **1.36M** | **0.266** | **0.635** |
39
+
40
+ Both models were evaluated at 320x240 (the teacher's predictions were made at 392x294 and then resized).
41
+
42
+ ## Training
43
+ - **Data:** about 2.8k DIODE indoor and outdoor images. Labels were pseudo-labels from the teacher, so no ground truth was used in training.
44
+ - **Loss:** scale-and-shift-invariant L1 (MiDaS median/MAD normalization) plus a multi-scale gradient-matching loss.
45
+ - **Optimizer and schedule:** AdamW with a OneCycle schedule, 15 epochs, batch size 16, 288x224 random crops, horizontal flips and color jitter. The best checkpoint was from epoch 12.
46
+ - **Encoder:** `mobilenetv4_conv_small.e2400_r224_in1k`, initialized from ImageNet.
47
+
48
+ ## Limitations
49
+ - Outputs relative depth only; it does not predict metric depth.
50
+ - Low resolution, so thin structures such as chair legs and wires may be missed.
51
+ - Trained on a small dataset, so it may degrade in unusual domains such as underwater scenes or extreme lighting.
52
+ - Not safety-certified. Do not use it as the only collision-avoidance sensor.
53
+
54
+ ## Files
55
+ `model.safetensors` (PyTorch weights), `tinydepth.onnx`, `model.py`, `inference.py`
demo.jpg ADDED

Git LFS Details

  • SHA256: c74fa3320f28695400eb5839561fc16e315c5b202825ce97627c3a881ea96442
  • Pointer size: 131 Bytes
  • Size of remote file: 186 kB
inference.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run TinyDepth on an image or webcam.
2
+
3
+ python inference.py image.jpg # writes image_depth.png
4
+ python inference.py --webcam # live view (q to quit)
5
+ python inference.py image.jpg --onnx # use ONNX Runtime (no torch needed beyond this script)
6
+ """
7
+ import sys
8
+ import cv2
9
+ import numpy as np
10
+
11
+ MEAN = np.array([0.485, 0.456, 0.406], np.float32)
12
+ STD = np.array([0.229, 0.224, 0.225], np.float32)
13
+ W, H = 320, 240
14
+
15
+
16
+ def load(use_onnx):
17
+ if use_onnx:
18
+ import onnxruntime as ort
19
+ sess = ort.InferenceSession("tinydepth.onnx", providers=["CPUExecutionProvider"])
20
+ return lambda x: sess.run(None, {"image": x})[0][0]
21
+ import torch
22
+ from safetensors.torch import load_file
23
+ from model import TinyDepth
24
+ m = TinyDepth(pretrained=False)
25
+ m.load_state_dict(load_file("model.safetensors"))
26
+ m.eval()
27
+ return lambda x: m(torch.from_numpy(x)).detach().numpy()[0]
28
+
29
+
30
+ def predict(fn, bgr):
31
+ rgb = cv2.cvtColor(cv2.resize(bgr, (W, H), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2RGB)
32
+ x = ((rgb.astype(np.float32) / 255 - MEAN) / STD).transpose(2, 0, 1)[None]
33
+ disp = fn(np.ascontiguousarray(x)) # relative inverse depth: larger = closer
34
+ disp = cv2.resize(disp, (bgr.shape[1], bgr.shape[0]))
35
+ vis = cv2.applyColorMap(cv2.normalize(disp, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8), cv2.COLORMAP_INFERNO)
36
+ return disp, vis
37
+
38
+
39
+ if __name__ == "__main__":
40
+ fn = load("--onnx" in sys.argv)
41
+ if "--webcam" in sys.argv:
42
+ cap = cv2.VideoCapture(0)
43
+ while True:
44
+ ok, frame = cap.read()
45
+ if not ok: break
46
+ _, vis = predict(fn, frame)
47
+ cv2.imshow("TinyDepth", np.hstack([frame, vis]))
48
+ if cv2.waitKey(1) & 0xFF == ord("q"): break
49
+ else:
50
+ path = [a for a in sys.argv[1:] if not a.startswith("--")][0]
51
+ _, vis = predict(fn, cv2.imread(path))
52
+ out = path.rsplit(".", 1)[0] + "_depth.png"
53
+ cv2.imwrite(out, vis)
54
+ print("wrote", out)
model.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TinyDepth: MobileNetV4-Small encoder + lightweight depthwise FPN decoder for relative (disparity) depth."""
2
+ import timm
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def dwconv(cin, cout):
9
+ """Depthwise-separable 3x3 conv block (cheap on CPU / edge NPUs)."""
10
+ return nn.Sequential(
11
+ nn.Conv2d(cin, cin, 3, padding=1, groups=cin, bias=False), nn.BatchNorm2d(cin), nn.ReLU(inplace=True),
12
+ nn.Conv2d(cin, cout, 1, bias=False), nn.BatchNorm2d(cout), nn.ReLU(inplace=True),
13
+ )
14
+
15
+
16
+ class TinyDepth(nn.Module):
17
+ def __init__(self, backbone="mobilenetv4_conv_small.e2400_r224_in1k", dec_ch=64, pretrained=True):
18
+ super().__init__()
19
+ self.encoder = timm.create_model(backbone, pretrained=pretrained, features_only=True, out_indices=(0, 1, 2, 3, 4))
20
+ chs = self.encoder.feature_info.channels() # strides 2,4,8,16,32
21
+ self.lateral = nn.ModuleList([nn.Conv2d(c, dec_ch, 1) for c in chs])
22
+ self.fuse = nn.ModuleList([dwconv(dec_ch, dec_ch) for _ in chs[:-1]])
23
+ self.head = nn.Sequential(
24
+ dwconv(dec_ch, 32),
25
+ nn.Conv2d(32, 1, 3, padding=1),
26
+ nn.ReLU(), # disparity is non-negative
27
+ )
28
+
29
+ def forward(self, x):
30
+ feats = self.encoder(x)
31
+ y = self.lateral[-1](feats[-1])
32
+ for i in range(len(feats) - 2, -1, -1):
33
+ y = F.interpolate(y, size=feats[i].shape[-2:], mode="bilinear", align_corners=False)
34
+ y = self.fuse[i](y + self.lateral[i](feats[i]))
35
+ y = self.head(y) # head runs at stride 2; upsample only the 1-channel map (much cheaper on CPU)
36
+ y = F.interpolate(y, size=x.shape[-2:], mode="bilinear", align_corners=False)
37
+ return y[:, 0] # (B, H, W) relative inverse depth
38
+
39
+
40
+ if __name__ == "__main__":
41
+ m = TinyDepth()
42
+ print("channels", m.encoder.feature_info.channels())
43
+ print(f"params {sum(p.numel() for p in m.parameters())/1e6:.2f}M")
44
+ print(m(torch.randn(2, 3, 240, 320)).shape)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ee4eeea562be28ff6c800c1ece38498da5f88d6d99fa545e8dc7c4aa0d02ae3
3
+ size 5571364
tinydepth.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a021b590c8fea494aae5764ca632a1fdbb9c509932396c295d58f810f390c6af
3
+ size 5431929