update video writer
Browse filesFiles changed (4)
12 unmodified lines131415161718192021222324252646 unmodified lines7374757677787980811 unmodified line8384858687888912 unmodified lines# limitations under the License.import spacesimport gradio as grimport numpy as npimport osimport torchfrom video_depth_anything.video_depth import VideoDepthAnythingfrom utils.dc_utils import read_video_frames, vis_sequence_depth, save_videofrom huggingface_hub import hf_hub_download46 unmodified linesinput_size: int = 518,):frames, target_fps = read_video_frames(input_video, max_len, target_fps, max_res)depth_list, fps = video_depth_anything.infer_video_depth(frames, target_fps, input_size=input_size, device=DEVICE)depth_list = np.stack(depth_list, axis=0)vis = vis_sequence_depth(depth_list)video_name = os.path.basename(input_video)if not os.path.exists(output_dir):os.makedirs(output_dir)1 unmodified lineprocessed_video_path = os.path.join(output_dir, os.path.splitext(video_name)[0]+'_src.mp4')depth_vis_path = os.path.join(output_dir, os.path.splitext(video_name)[0]+'_vis.mp4')save_video(frames, processed_video_path, fps=fps)save_video(vis, depth_vis_path, fps=fps)return [processed_video_path, depth_vis_path]12 unmodified lines131415161718192021222324252646 unmodified lines73747576777879801 unmodified line8283848586878889909112 unmodified lines# limitations under the License.import spacesimport gradio as grimport gcimport numpy as npimport osimport torchfrom video_depth_anything.video_depth import VideoDepthAnythingfrom utils.dc_utils import read_video_frames, save_videofrom huggingface_hub import hf_hub_download46 unmodified linesinput_size: int = 518,):frames, target_fps = read_video_frames(input_video, max_len, target_fps, max_res)depths, fps = video_depth_anything.infer_video_depth(frames, target_fps, input_size=input_size, device=DEVICE)video_name = os.path.basename(input_video)if not os.path.exists(output_dir):os.makedirs(output_dir)1 unmodified lineprocessed_video_path = os.path.join(output_dir, os.path.splitext(video_name)[0]+'_src.mp4')depth_vis_path = os.path.join(output_dir, os.path.splitext(video_name)[0]+'_vis.mp4')save_video(frames, processed_video_path, fps=fps)save_video(depths, depth_vis_path, fps=fps, is_depths=True)gc.collect()torch.cuda.empty_cache()return [processed_video_path, depth_vis_path]
6 unmodified lines789101112136 unmodified linesmatplotlibhuggingface_hubpillowmediapydecordxformerseinops6 unmodified lines78910111213146 unmodified linesmatplotlibhuggingface_hubpillowimageioimageio-ffmpegdecordxformerseinops
2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283842 unmodified lines## This file may have been modified by ByteDance Ltd. and/or its affiliates on [date of modification]# Original file is released under [ MIT License license], with the full license text available at [https://github.com/Tencent/DepthCrafter?tab=License-1-ov-file].from typing import Union, Listimport tempfileimport numpy as npimport PIL.Imageimport matplotlib.cm as cmimport mediapyimport torchfrom decord import VideoReader, cpudef read_video_frames(video_path, process_length, target_fps=-1, max_res=-1, dataset="open"):vid = VideoReader(video_path, ctx=cpu(0))print("==> original video shape: ", (len(vid), *vid.get_batch([0]).shape[1:]))original_height, original_width = vid.get_batch([0]).shape[1:3]height = original_heightwidth = original_widthif max_res > 0 and max(height, width) > max_res:scale = max_res / max(original_height, original_width)height = round(original_height * scale)width = round(original_width * scale)vid = VideoReader(video_path, ctx=cpu(0), width=width, height=height)fps = vid.get_avg_fps() if target_fps == -1 else target_fpsstride = round(vid.get_avg_fps() / fps)stride = max(stride, 1)frames_idx = list(range(0, len(vid), stride))if process_length != -1 and process_length < len(frames_idx):frames_idx = frames_idx[:process_length]print(f"==> final processing shape: {len(frames_idx), *vid.get_batch([0]).shape[1:]}")frames = vid.get_batch(frames_idx).asnumpy()return frames, fpsdef save_video(video_frames: Union[List[np.ndarray], List[PIL.Image.Image]],output_video_path: str = None,fps: int = 10,crf: int = 18,) -> str:if output_video_path is None:output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").nameif isinstance(video_frames[0], np.ndarray):video_frames = [frame.astype(np.uint8) for frame in video_frames]elif isinstance(video_frames[0], PIL.Image.Image):video_frames = [np.array(frame) for frame in video_frames]mediapy.write_video(output_video_path, video_frames, fps=fps, crf=crf)return output_video_pathclass ColorMapper:# a color mapper to map depth values to a certain colormapdef __init__(self, colormap: str = "inferno"):self.colormap = torch.tensor(cm.get_cmap(colormap).colors)def apply(self, image: torch.Tensor, v_min=None, v_max=None):# assert len(image.shape) == 2if v_min is None:v_min = image.min()if v_max is None:v_max = image.max()image = (image - v_min) / (v_max - v_min)image = (image * 255).long()image = self.colormap[image] * 255return imagedef vis_sequence_depth(depths: np.ndarray, v_min=None, v_max=None):visualizer = ColorMapper()if v_min is None:v_min = depths.min()if v_max is None:v_max = depths.max()res = visualizer.apply(torch.tensor(depths), v_min=v_min, v_max=v_max).numpy()return res2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485862 unmodified lines## This file may have been modified by ByteDance Ltd. and/or its affiliates on [date of modification]# Original file is released under [ MIT License license], with the full license text available at [https://github.com/Tencent/DepthCrafter?tab=License-1-ov-file].import numpy as npimport matplotlib.cm as cmimport imageiotry:from decord import VideoReader, cpuDECORD_AVAILABLE = Trueexcept:import cv2DECORD_AVAILABLE = Falsedef ensure_even(value):return value if value % 2 == 0 else value + 1def read_video_frames(video_path, process_length, target_fps=-1, max_res=-1):if DECORD_AVAILABLE:vid = VideoReader(video_path, ctx=cpu(0))original_height, original_width = vid.get_batch([0]).shape[1:3]height = original_heightwidth = original_widthif max_res > 0 and max(height, width) > max_res:scale = max_res / max(original_height, original_width)height = ensure_even(round(original_height * scale))width = ensure_even(round(original_width * scale))vid = VideoReader(video_path, ctx=cpu(0), width=width, height=height)fps = vid.get_avg_fps() if target_fps == -1 else target_fpsstride = round(vid.get_avg_fps() / fps)stride = max(stride, 1)frames_idx = list(range(0, len(vid), stride))if process_length != -1 and process_length < len(frames_idx):frames_idx = frames_idx[:process_length]frames = vid.get_batch(frames_idx).asnumpy()else:cap = cv2.VideoCapture(video_path)original_fps = cap.get(cv2.CAP_PROP_FPS)original_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))original_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))if max_res > 0 and max(original_height, original_width) > max_res:scale = max_res / max(original_height, original_width)height = round(original_height * scale)width = round(original_width * scale)fps = original_fps if target_fps < 0 else target_fpsstride = max(round(original_fps / fps), 1)frames = []frame_count = 0while cap.isOpened():ret, frame = cap.read()if not ret or (process_length > 0 and frame_count >= process_length):breakif frame_count % stride == 0:frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert BGR to RGBif max_res > 0 and max(original_height, original_width) > max_res:frame = cv2.resize(frame, (width, height)) # Resize frameframes.append(frame)frame_count += 1cap.release()frames = np.stack(frames, axis=0)return frames, fpsdef save_video(frames, output_video_path, fps=10, is_depths=False):writer = imageio.get_writer(output_video_path, fps=fps, macro_block_size=1, codec='libx264', ffmpeg_params=['-crf', '18'])if is_depths:colormap = np.array(cm.get_cmap("inferno").colors)d_min, d_max = frames.min(), frames.max()for i in range(frames.shape[0]):depth = frames[i]depth_norm = ((depth - d_min) / (d_max - d_min) * 255).astype(np.uint8)depth_vis = (colormap[depth_norm] * 255).astype(np.uint8)writer.append_data(depth_vis)else:for i in range(frames.shape[0]):writer.append_data(frames[i])writer.close()
151 unmodified lines152153154155156151 unmodified linesdepth_list = depth_list_alignedreturn depth_list[:org_video_len], target_fps151 unmodified lines152153154155156151 unmodified linesdepth_list = depth_list_alignedreturn np.stack(depth_list[:org_video_len], axis=0), target_fps
app.py+8-6
requirements.txt+2-1
utils/dc_utils.py+67-65
video_depth_anything/video_depth.py+1-1