Spaces:
Sleeping
Sleeping
Update app.py
Browse filesLower the memory usage by processing each video frame at one time.
32 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656667683 unmodified lines727374757677785 unmodified lines848586878889906 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112211 unmodified lines13413513613713813932 unmodified linesstitched_video_path = Noneif stitch:# Ensure target_fps is valid (positive) or use original fpssafe_target_fps = max(1, target_fps) if target_fps > 0 else -1# For stitching: read the original video in full resolution (without downscaling).full_frames, original_fps = read_video_frames(processed_video, max_len, target_fps, max_res=-1)depths, _ = read_video_frames(depth_vis_video, max_len, target_fps, max_res=-1)# Use original_fps if target_fps wasn't specifiedif target_fps <= 0:target_fps = original_fpsprint(f"Video fps: {original_fps}, target fps: {target_fps}")print(f"Depth frame shape: {depths[0].shape if len(depths) > 0 else 'No frames'}, "f"dtype: {depths[0].dtype if len(depths) > 0 else 'N/A'}, "f"min: {depths.min() if len(depths) > 0 else 'N/A'}, "f"max: {depths.max() if len(depths) > 0 else 'N/A'}")if len(depths) == 0 or len(full_frames) == 0:print("Error: No frames to process in either RGB or depth video")return None# For each frame, create a visual depth image from the inferenced depths.d_min, d_max = np.min(depths), np.max(depths)print(f"Depth range: min={d_min}, max={d_max}, diff={d_max-d_min}")stitched_frames = []for i in range(min(len(full_frames), len(depths))):rgb_full = full_frames[i] # Full-resolution RGB frame.depth_frame = depths[i] # Already in uint8 formatif grayscale:if convert_from_color:# Convert to grayscale if it's a color image3 unmodified lines# Assume it's already the right formatdepth_vis = depth_frameelse:if depth_frame.max() > 0: # Ensure we have valid depth data# Use the inferno colormap if requestedcmap = matplotlib.colormaps.get_cmap("inferno")# Convert to single channel first5 unmodified lineselse:# If zero depth, just use the originaldepth_vis = depth_frame# Apply Gaussian blur if requestedif blur > 0:6 unmodified linesdepth_vis_resized = cv2.resize(depth_vis, (W_full, H_full))depth_vis_resized = depth_vis_resized.astype(np.uint8) # Ensure uint8if len(depth_vis_resized.shape) == 2:depth_vis_resized = cv2.cvtColor(depth_vis_resized, cv2.COLOR_GRAY2BGR)# Ensure both are the same type (commonly uint8):if rgb_full.dtype != depth_vis_resized.dtype:depth_vis_resized = depth_vis_resized.astype(rgb_full.dtype)# Now safely concatenate.stitched = cv2.hconcat([rgb_full, depth_vis_resized])stitched_frames.append(stitched)del rgb_full, depth_vis_resized, stitchedgc.collect() # Force Python to free unused memorystitched_frames = np.array(stitched_frames)# Use only the first 20 characters of the base name for the output filename and append '_RGBD.mp4'base_name = os.path.splitext(video_name)[0]short_name = base_name[:20]stitched_video_path = os.path.join(output_dir, short_name + '_RGBD.mp4')save_video(stitched_frames, stitched_video_path, fps=target_fps)# Merge audio from the input video into the stitched video using ffmpeg.temp_audio_path = stitched_video_path.replace('_RGBD.mp4', '_RGBD_audio.mp4')11 unmodified lines]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)os.replace(temp_audio_path, stitched_video_path)# Return stitched video.return stitched_video_path32 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161173 unmodified lines1211221231241251261275 unmodified lines1331341351361371386 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017111 unmodified lines18318418518618718818919032 unmodified linesstitched_video_path = Noneif stitch:# Process videos frame by framecap_rgb = cv2.VideoCapture(processed_video)cap_depth = cv2.VideoCapture(depth_vis_video)if not cap_rgb.isOpened() or not cap_depth.isOpened():print("Error: Could not open one or both videos")return None# Get video propertiesoriginal_fps = cap_rgb.get(cv2.CAP_PROP_FPS)if target_fps <= 0:target_fps = original_fps# Calculate stride for frame skippingstride = max(round(original_fps / target_fps), 1) if target_fps > 0 else 1# Get frame counts for progress reportingtotal_frames_rgb = int(cap_rgb.get(cv2.CAP_PROP_FRAME_COUNT))print(f"Video fps: {original_fps}, target fps: {target_fps}, total frames: {total_frames_rgb}")# Set up video writerbase_name = os.path.splitext(video_name)[0]short_name = base_name[:20]stitched_video_path = os.path.join(output_dir, short_name + '_RGBD.mp4')# Get first frame to determine dimensionsret_rgb, first_frame_rgb = cap_rgb.read()ret_depth, first_frame_depth = cap_depth.read()if not ret_rgb or not ret_depth:print("Error: Could not read first frame from one or both videos")return None# Reset video capturescap_rgb.set(cv2.CAP_PROP_POS_FRAMES, 0)cap_depth.set(cv2.CAP_PROP_POS_FRAMES, 0)# Get output dimensionsH_full, W_full = first_frame_rgb.shape[:2]output_width = W_full * 2 # RGB and depth side by sideoutput_height = H_full# Initialize video writerfourcc = cv2.VideoWriter_fourcc(*'mp4v')out = cv2.VideoWriter(stitched_video_path, fourcc, target_fps, (output_width, output_height))# Process frames one by oneframe_count = 0processed_count = 0while True:# Read framesret_rgb, rgb_full = cap_rgb.read()ret_depth, depth_frame = cap_depth.read()# Break if either video endsif not ret_rgb or not ret_depth:break# Skip frames based on strideframe_count += 1if frame_count % stride != 0:continueprocessed_count += 1# Set max_len limit if specifiedif max_len > 0 and processed_count > max_len:break# Process RGB frame - resize if max_res is specifiedif max_res > 0:h, w = rgb_full.shape[:2]if max(h, w) > max_res:scale = max_res / max(h, w)new_h, new_w = int(h * scale), int(w * scale)rgb_full = cv2.resize(rgb_full, (new_w, new_h))# Process depth frame based on settings (assuming always 3-channel)if grayscale:if convert_from_color:# Convert to grayscale if it's a color image3 unmodified lines# Assume it's already the right formatdepth_vis = depth_frameelse:if np.max(depth_frame) > 0: # Ensure we have valid depth data# Use the inferno colormap if requestedcmap = matplotlib.colormaps.get_cmap("inferno")# Convert to single channel first5 unmodified lineselse:# If zero depth, just use the originaldepth_vis = depth_frame# Apply Gaussian blur if requestedif blur > 0:6 unmodified linesdepth_vis_resized = cv2.resize(depth_vis, (W_full, H_full))depth_vis_resized = depth_vis_resized.astype(np.uint8) # Ensure uint8# Concatenate framesstitched = cv2.hconcat([rgb_full, depth_vis_resized])# Write frameout.write(stitched)# Free memorydel rgb_full, depth_vis, depth_vis_resized, stitched# Progress reportif processed_count % 10 == 0:print(f"Processed {processed_count} frames...")# Force garbage collection periodicallyif processed_count % 50 == 0:gc.collect()# Release resourcescap_rgb.release()cap_depth.release()out.release()# Merge audio from the input video into the stitched video using ffmpeg.temp_audio_path = stitched_video_path.replace('_RGBD.mp4', '_RGBD_audio.mp4')11 unmodified lines]subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)os.replace(temp_audio_path, stitched_video_path)print(f"Completed processing {processed_count} frames")# Return stitched video.return stitched_video_path
app.py+92-41