File size: 8,050 Bytes
beed6f0
 
 
 
 
 
 
 
 
 
 
095b09d
beed6f0
 
 
 
 
 
 
 
 
095b09d
beed6f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
095b09d
 
 
 
 
 
 
 
 
 
 
 
 
beed6f0
 
 
 
 
 
 
 
095b09d
 
beed6f0
 
 
 
 
095b09d
beed6f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
095b09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beed6f0
 
 
095b09d
 
 
beed6f0
 
 
 
 
 
 
 
 
 
 
 
 
095b09d
 
 
beed6f0
 
 
 
 
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Export metric DAV2 Small depth for every video frame."""
import argparse
import csv
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from depth_anything_v2.dpt import DepthAnythingV2
from geometry import slope_features

MODEL = 'depth-anything/Depth-Anything-V2-Metric-VKITTI-Small'
WEIGHTS = 'depth_anything_v2_metric_vkitti_vits.pth'


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--video', type=Path, required=True)
    parser.add_argument('--frames-csv', type=Path)
    parser.add_argument('--geometry-csv', type=Path, help='Per-frame intrinsics and optional camera up vectors')
    parser.add_argument('--out', type=Path, required=True)
    parser.add_argument('--checkpoint', type=Path, help='Use local weights instead of downloading')
    parser.add_argument('--limit', type=int, help='Only process the first N frames for a trial')
    args = parser.parse_args()
    if args.limit is not None and args.limit <= 0:
        parser.error('--limit must be positive')
    if args.out.exists() and any(args.out.iterdir()):
        parser.error('--out must be empty to avoid mixing clips')

    capture = cv2.VideoCapture(str(args.video))
    count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = capture.get(cv2.CAP_PROP_FPS)
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
    if not capture.isOpened() or count <= 0 or fps <= 0:
        raise ValueError(f'Cannot read video: {args.video}')
    source = None
    if args.frames_csv:
        with args.frames_csv.open(encoding='utf-8-sig', newline='') as stream:
            source = list(csv.DictReader(stream))
        if [int(row['frame_idx']) for row in source] != list(range(count)):
            raise ValueError('CSV frame_idx must match every video frame in order')

    geometry = None
    gravity_aligned = False
    if args.geometry_csv:
        with args.geometry_csv.open(encoding='utf-8-sig', newline='') as stream:
            geometry = list(csv.DictReader(stream))
        if [int(row['frame_idx']) for row in geometry] != list(range(count)):
            raise ValueError('Geometry CSV must match every video frame in order')
        gravity_aligned = all(key in geometry[0] for key in ['up_x','up_y','up_z'])
        for index, params in enumerate(geometry):
            if (int(params['width']), int(params['height'])) != (width, height):
                raise ValueError('Intrinsics resolution must match the video; use native fields for native video')
            if source is not None and 'stamp' in params and abs(float(params['stamp'])-float(source[index]['stamp'])) > 1e-5:
                raise ValueError(f'Geometry/frame timestamps differ at frame {index}')
    torch.set_num_threads(4)
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    checkpoint = str(args.checkpoint) if args.checkpoint else hf_hub_download(MODEL, WEIGHTS)
    model = DepthAnythingV2(encoder='vits', features=64,
                           out_channels=[48, 96, 192, 384], max_depth=80)
    model.load_state_dict(torch.load(checkpoint, map_location='cpu', weights_only=True))
    model = model.to(device).eval()
    (args.out / 'depth').mkdir(parents=True)
    if geometry is not None:
        (args.out / 'terrain').mkdir()
    # Compact previews; raw arrays retain the source resolution.
    pw = min(width, 960) // 2 * 2
    ph = round(height * pw / width) // 2 * 2
    writers = [cv2.VideoWriter(str(args.out / name), cv2.VideoWriter_fourcc(*'mp4v'),
                              fps, size) for name, size in [
                                  ('depth.mp4', (pw, ph)), ('preview.mp4', (pw * (3 if geometry is not None else 2), ph))]]
    rows = []
    try:
        if not all(writer.isOpened() for writer in writers):
            raise RuntimeError('MP4 encoder could not be opened')
        total = min(count, args.limit) if args.limit else count
        with torch.inference_mode():
            for index in range(total):
                ok, image = capture.read()
                if not ok:
                    raise RuntimeError(f'Cannot decode frame {index}')
                depth = model.infer_image(image, 518).astype(np.float32)
                if depth.shape != (height, width) or not np.isfinite(depth).all():
                    raise RuntimeError(f'Invalid depth at frame {index}')
                name = f'depth/frame{index:06d}.npy'
                np.save(args.out / name, depth)
                colored = cv2.applyColorMap(np.uint8(np.clip(depth / 50, 0, 1) * 255),
                                           cv2.COLORMAP_TURBO)
                colored = cv2.resize(colored, (pw, ph))
                writers[0].write(colored)
                panels = [cv2.resize(image, (pw, ph)), colored]
                if geometry is not None:
                    params = geometry[index]
                    fx,fy,cx,cy = [float(params[key]) for key in ['fx','fy','cx','cy']]
                    k = np.array([[fx,0,cx],[0,fy,cy],[0,0,1]], dtype=np.float64)
                    up = np.array([float(params[key]) for key in ['up_x','up_y','up_z']]) if gravity_aligned else np.array([0.,-1.,0.])
                    if not np.isfinite(k).all() or fx <= 0 or fy <= 0 or not np.isfinite(up).all() or np.linalg.norm(up) == 0:
                        raise ValueError(f'Invalid geometry at frame {index}')
                    slope, valid = slope_features(depth, k, up)
                    field = 'slope_degrees' if gravity_aligned else 'slope_degrees_proxy'
                    np.savez_compressed(args.out / 'terrain' / f'frame{index:06d}.npz',
                                        **{field: slope.astype(np.float16), 'valid': valid})
                    pixels = np.uint8(np.clip(np.nan_to_num(slope) / 90, 0, 1) * 255)
                    panel = cv2.applyColorMap(pixels, cv2.COLORMAP_TURBO)
                    panel[~valid] = 0
                    panel = cv2.resize(panel, (pw, ph))
                    cv2.putText(panel, 'Slope estimate 0-90 deg' if gravity_aligned else 'Slope proxy 0-90 deg',
                                (8,24), cv2.FONT_HERSHEY_SIMPLEX, .6, (255,255,255), 1)
                    panels.append(panel)
                writers[1].write(np.hstack(panels))
                row = dict(source[index]) if source is not None else dict(frame_idx=index)
                row.update(source_frame=index, timestamp_s=float(row['stamp']) if source else index / fps,
                           depth=name, height=height, width=width, depth_units='meters')
                if geometry is not None:
                    row.update(terrain=f'terrain/frame{index:06d}.npz',
                               geometry_reference='recorded_intrinsics_arkit_gravity' if gravity_aligned else 'recorded_intrinsics_assumed_up')
                rows.append(row)
                print(f'{index + 1}/{total}', flush=True)
    finally:
        capture.release()
        for writer in writers:
            writer.release()
    with (args.out / 'frames.csv').open('w', encoding='utf-8', newline='') as stream:
        writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    report = dict(model=MODEL, device=device, source_frames=count, exported_frames=len(rows),
                  source_fps=fps, depth_shape=[height, width], depth_dtype='float32',
                  depth_units='meters (model prediction)', input_size=518,
                  preview_color_range_m=[0, 50], preview_layout='RGB | depth | slope' if geometry is not None else 'RGB | depth',
                  recorded_intrinsics_used=geometry is not None, gravity_aligned=gravity_aligned,
                  depth_scale_validated=False,
                  timestamp_source='CSV stamp' if source else 'frame index / video FPS')
    (args.out / 'run.json').write_text(json.dumps(report, indent=2), encoding='utf-8')


if __name__ == '__main__':
    main()