Spaces:
Sleeping
Sleeping
| import cv2 | |
| import os | |
| import logging | |
| # Setup logging | |
| logging.basicConfig( | |
| filename="app.log", | |
| level=logging.INFO, | |
| format="%(asctime)s - %(levelname)s - %(message)s" | |
| ) | |
| # Global video capture object | |
| video_cap = None | |
| current_frame_index = 0 | |
| def preload_video(video_path): | |
| """ | |
| Preload the video file. | |
| Args: | |
| video_path: Path to the video file | |
| Returns: | |
| str: Status message | |
| """ | |
| global video_cap, current_frame_index | |
| try: | |
| if not os.path.exists(video_path): | |
| raise FileNotFoundError(f"Video file not found at {video_path}") | |
| video_cap = cv2.VideoCapture(video_path) | |
| if not video_cap.isOpened(): | |
| raise RuntimeError("Failed to open video file.") | |
| current_frame_index = 0 | |
| total_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| logging.info(f"Preloaded video: {video_path} with {total_frames} frames.") | |
| return f"Successfully loaded video: {video_path} ({total_frames} frames)" | |
| except Exception as e: | |
| logging.error(f"Error preloading video: {str(e)}") | |
| return f"Error loading video: {str(e)}" | |
| def get_next_video_frame(): | |
| """ | |
| Get the next frame from the video. | |
| Returns: | |
| numpy array: Frame if successful, None otherwise | |
| """ | |
| global video_cap, current_frame_index | |
| if video_cap is None or not video_cap.isOpened(): | |
| logging.error("Video capture not initialized.") | |
| return None | |
| try: | |
| # Set frame position | |
| video_cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame_index) | |
| ret, frame = video_cap.read() | |
| if not ret: | |
| # Loop back to the start | |
| current_frame_index = 0 | |
| video_cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame_index) | |
| ret, frame = video_cap.read() | |
| if not ret: | |
| raise RuntimeError("Failed to read frame from video.") | |
| current_frame_index += 1 | |
| logging.debug(f"Retrieved frame {current_frame_index} from video.") | |
| return frame | |
| except Exception as e: | |
| logging.error(f"Error retrieving frame: {str(e)}") | |
| return None | |
| def reset_video_index(): | |
| """ | |
| Reset the frame index to the beginning. | |
| """ | |
| global current_frame_index | |
| current_frame_index = 0 | |
| logging.info("Reset video frame index to 0.") | |
| def release_video(): | |
| """ | |
| Release the video capture object. | |
| """ | |
| global video_cap | |
| if video_cap is not None: | |
| video_cap.release() | |
| video_cap = None | |
| logging.info("Released video capture object.") |