mtwohey2 commited on
Commit
344feb9
·
verified ·
1 Parent(s): 9820c08

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -0
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gc
3
+ import torch
4
+ import cv2
5
+ import gradio as gr
6
+ import numpy as np
7
+ import matplotlib.cm as cm
8
+ import matplotlib # New import for the updated colormap API
9
+ import subprocess
10
+ import sys
11
+ import spaces
12
+
13
+ from video_depth_anything.video_depth import VideoDepthAnything
14
+ from utils.dc_utils import read_video_frames, save_video
15
+ from huggingface_hub import hf_hub_download
16
+
17
+ # Examples for the Gradio Demo.
18
+ # Each example now contains 8 parameters:
19
+ # [video_path, max_len, target_fps, max_res, stitch, grayscale, convert_from_color, blur]
20
+ examples = [
21
+ ['assets/example_videos/octopus_01.mp4', -1, -1, 1280, True, True, True, 0.3],
22
+ ['assets/example_videos/chicken_01.mp4', -1, -1, 1280, True, True, True, 0.3],
23
+ ['assets/example_videos/gorilla_01.mp4', -1, -1, 1280, True, True, True, 0.3],
24
+ ['assets/example_videos/davis_rollercoaster.mp4', -1, -1, 1280, True, True, True, 0.3],
25
+ ['assets/example_videos/Tokyo-Walk_rgb.mp4', -1, -1, 1280, True, True, True, 0.3],
26
+ ['assets/example_videos/4158877-uhd_3840_2160_30fps_rgb.mp4', -1, -1, 1280, True, True, True, 0.3],
27
+ ['assets/example_videos/4511004-uhd_3840_2160_24fps_rgb.mp4', -1, -1, 1280, True, True, True, 0.3],
28
+ ['assets/example_videos/1753029-hd_1920_1080_30fps.mp4', -1, -1, 1280, True, True, True, 0.3],
29
+ ['assets/example_videos/davis_burnout.mp4', -1, -1, 1280, True, True, True, 0.3],
30
+ ['assets/example_videos/example_5473765-l.mp4', -1, -1, 1280, True, True, True, 0.3],
31
+ ['assets/example_videos/Istanbul-26920.mp4', -1, -1, 1280, True, True, True, 0.3],
32
+ ['assets/example_videos/obj_1.mp4', -1, -1, 1280, True, True, True, 0.3],
33
+ ['assets/example_videos/sheep_cut1.mp4', -1, -1, 1280, True, True, True, 0.3],
34
+ ]
35
+
36
+ # Use GPU if available; otherwise, use CPU.
37
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
38
+
39
+ # Model configuration for different encoder variants.
40
+ model_configs = {
41
+ 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
42
+ 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
43
+ }
44
+ encoder2name = {
45
+ 'vits': 'Small',
46
+ 'vitl': 'Large',
47
+ }
48
+ encoder = 'vitl'
49
+ model_name = encoder2name[encoder]
50
+
51
+ # Initialize the model.
52
+ video_depth_anything = VideoDepthAnything(**model_configs[encoder])
53
+ filepath = hf_hub_download(
54
+ repo_id=f"depth-anything/Video-Depth-Anything-{model_name}",
55
+ filename=f"video_depth_anything_{encoder}.pth",
56
+ repo_type="model"
57
+ )
58
+ video_depth_anything.load_state_dict(torch.load(filepath, map_location='cpu'))
59
+ video_depth_anything = video_depth_anything.to(DEVICE).eval()
60
+
61
+ title = "# Video Depth Anything + RGBD sbs output"
62
+ description = """**Video Depth Anything** + RGBD sbs output for viewing with Looking Glass Factory displays.
63
+ Please refer to our [paper](https://arxiv.org/abs/2501.12375), [project page](https://videodepthanything.github.io/), and [github](https://github.com/DepthAnything/Video-Depth-Anything) for more details."""
64
+
65
+ @spaces.GPU(enable_queue=True)
66
+
67
+ def infer_video_depth(
68
+ input_video: str,
69
+ max_len: int = -1,
70
+ target_fps: int = -1,
71
+ max_res: int = 1280,
72
+ stitch: bool = True,
73
+ grayscale: bool = True,
74
+ convert_from_color: bool = True,
75
+ blur: float = 0.3,
76
+ output_dir: str = './outputs',
77
+ input_size: int = 518,
78
+ ):
79
+ # 1. Read input video frames for inference (downscaled to max_res).
80
+ frames, target_fps = read_video_frames(input_video, max_len, target_fps, max_res)
81
+ # 2. Perform depth inference using the model.
82
+ depths, fps = video_depth_anything.infer_video_depth(frames, target_fps, input_size=input_size, device=DEVICE)
83
+
84
+ video_name = os.path.basename(input_video)
85
+ if not os.path.exists(output_dir):
86
+ os.makedirs(output_dir)
87
+
88
+ # Save the preprocessed (RGB) video and the generated depth visualization.
89
+ processed_video_path = os.path.join(output_dir, os.path.splitext(video_name)[0] + '_src.mp4')
90
+ depth_vis_path = os.path.join(output_dir, os.path.splitext(video_name)[0] + '_vis.mp4')
91
+ save_video(frames, processed_video_path, fps=fps)
92
+ save_video(depths, depth_vis_path, fps=fps, is_depths=True)
93
+
94
+ stitched_video_path = None
95
+ if stitch:
96
+ # For stitching: read the original video in full resolution (without downscaling).
97
+ full_frames, _ = read_video_frames(input_video, max_len, target_fps, max_res=-1)
98
+ # For each frame, create a visual depth image from the inferenced depths.
99
+ d_min, d_max = depths.min(), depths.max()
100
+ stitched_frames = []
101
+ for i in range(min(len(full_frames), len(depths))):
102
+ rgb_full = full_frames[i] # Full-resolution RGB frame.
103
+ depth_frame = depths[i]
104
+ # Normalize the depth frame to the range [0, 255].
105
+ depth_norm = ((depth_frame - d_min) / (d_max - d_min) * 255).astype(np.uint8)
106
+ # Generate depth visualization:
107
+ if grayscale:
108
+ if convert_from_color:
109
+ # First, generate a color depth image using the inferno colormap,
110
+ # then convert that color image to grayscale.
111
+ cmap = matplotlib.colormaps.get_cmap("inferno")
112
+ depth_color = (cmap(depth_norm / 255.0)[..., :3] * 255).astype(np.uint8)
113
+ depth_gray = cv2.cvtColor(depth_color, cv2.COLOR_RGB2GRAY)
114
+ depth_vis = np.stack([depth_gray] * 3, axis=-1)
115
+ else:
116
+ # Directly generate a grayscale image from the normalized depth values.
117
+ depth_vis = np.stack([depth_norm] * 3, axis=-1)
118
+ else:
119
+ # Generate a color depth image using the inferno colormap.
120
+ cmap = matplotlib.colormaps.get_cmap("inferno")
121
+ depth_vis = (cmap(depth_norm / 255.0)[..., :3] * 255).astype(np.uint8)
122
+ # Apply Gaussian blur if requested.
123
+ if blur > 0:
124
+ kernel_size = int(blur * 20) * 2 + 1 # Ensures an odd kernel size.
125
+ depth_vis = cv2.GaussianBlur(depth_vis, (kernel_size, kernel_size), 0)
126
+ # Resize the depth visualization to match the full-resolution RGB frame.
127
+ H_full, W_full = rgb_full.shape[:2]
128
+ depth_vis_resized = cv2.resize(depth_vis, (W_full, H_full))
129
+ # Concatenate the full-resolution RGB frame (left) and the resized depth visualization (right).
130
+ stitched = cv2.hconcat([rgb_full, depth_vis_resized])
131
+ stitched_frames.append(stitched)
132
+ stitched_frames = np.array(stitched_frames)
133
+ # Use only the first 20 characters of the base name for the output filename and append '_RGBD.mp4'
134
+ base_name = os.path.splitext(video_name)[0]
135
+ short_name = base_name[:20]
136
+ stitched_video_path = os.path.join(output_dir, short_name + '_RGBD.mp4')
137
+ save_video(stitched_frames, stitched_video_path, fps=fps)
138
+
139
+ # Merge audio from the input video into the stitched video using ffmpeg.
140
+ temp_audio_path = stitched_video_path.replace('_RGBD.mp4', '_RGBD_audio.mp4')
141
+ cmd = [
142
+ "ffmpeg",
143
+ "-y",
144
+ "-i", stitched_video_path,
145
+ "-i", input_video,
146
+ "-c:v", "copy",
147
+ "-c:a", "aac",
148
+ "-map", "0:v:0",
149
+ "-map", "1:a:0?",
150
+ "-shortest",
151
+ temp_audio_path
152
+ ]
153
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
154
+ os.replace(temp_audio_path, stitched_video_path)
155
+
156
+ gc.collect()
157
+ torch.cuda.empty_cache()
158
+
159
+ # Return the preprocessed RGB video, depth visualization, and (if created) the stitched video.
160
+ return [processed_video_path, depth_vis_path, stitched_video_path]
161
+
162
+ def construct_demo():
163
+ with gr.Blocks(analytics_enabled=False) as demo:
164
+ gr.Markdown(title)
165
+ gr.Markdown(description)
166
+ gr.Markdown("### If you find this work useful, please help ⭐ the [Github Repo](https://github.com/DepthAnything/Video-Depth-Anything). Thanks for your attention!")
167
+
168
+ with gr.Row(equal_height=True):
169
+ with gr.Column(scale=1):
170
+ # Video input component for file upload.
171
+ input_video = gr.Video(label="Input Video")
172
+ with gr.Column(scale=2):
173
+ with gr.Row(equal_height=True):
174
+ processed_video = gr.Video(label="Preprocessed Video", interactive=False, autoplay=True, loop=True, show_share_button=True, scale=5)
175
+ depth_vis_video = gr.Video(label="Generated Depth Video", interactive=False, autoplay=True, loop=True, show_share_button=True, scale=5)
176
+ stitched_video = gr.Video(label="Stitched RGBD Video", interactive=False, autoplay=True, loop=True, show_share_button=True, scale=5)
177
+
178
+ with gr.Row(equal_height=True):
179
+ with gr.Column(scale=1):
180
+ with gr.Accordion("Advanced Settings", open=False):
181
+ max_len = gr.Slider(label="Max process length", minimum=-1, maximum=1000, value=-1, step=1)
182
+ target_fps = gr.Slider(label="Target FPS", minimum=-1, maximum=30, value=-1, step=1)
183
+ max_res = gr.Slider(label="Max side resolution", minimum=480, maximum=1920, value=1280, step=1)
184
+ stitch_option = gr.Checkbox(label="Stitch RGB & Depth Videos", value=True)
185
+ grayscale_option = gr.Checkbox(label="Output Depth as Grayscale", value=True)
186
+ convert_from_color_option = gr.Checkbox(label="Convert Grayscale from Color", value=True)
187
+ blur_slider = gr.Slider(minimum=0, maximum=1, step=0.01, label="Depth Blur (can reduce edge artifacts on display)", value=0.3)
188
+ generate_btn = gr.Button("Generate")
189
+ with gr.Column(scale=2):
190
+ pass
191
+
192
+ gr.Examples(
193
+ examples=examples,
194
+ inputs=[input_video, max_len, target_fps, max_res, stitch_option, grayscale_option, convert_from_color_option, blur_slider],
195
+ outputs=[processed_video, depth_vis_video, stitched_video],
196
+ fn=infer_video_depth,
197
+ cache_examples=False,
198
+ cache_mode="lazy",
199
+ )
200
+
201
+ generate_btn.click(
202
+ fn=infer_video_depth,
203
+ inputs=[input_video, max_len, target_fps, max_res, stitch_option, grayscale_option, convert_from_color_option, blur_slider],
204
+ outputs=[processed_video, depth_vis_video, stitched_video],
205
+ )
206
+
207
+ return demo
208
+
209
+ if __name__ == "__main__":
210
+ demo = construct_demo()
211
+ demo.queue(max_size=2).launch()