surveillance / services /video_service.py
lokesh341's picture
Update services/video_service.py
c374261
raw
history blame
2.17 kB
import cv2
import os
# Global variables
cap = None
frame_index = 0
current_video_path = None
def preload_video(video_path="sample.mp4"):
"""
Preload the video file.
Args:
video_path (str): Path to the video file.
Returns:
str: Status message indicating success or failure.
"""
global cap, frame_index, current_video_path
try:
# Reset previous capture if any
if cap is not None:
cap.release()
# Check if video file exists
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video file {video_path} not found. Please upload a video file named 'sample.mp4' or provide a different path.")
# Initialize video capture
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise RuntimeError(f"Failed to open video file {video_path}. Ensure the file is a valid video format (e.g., .mp4).")
frame_index = 0
current_video_path = video_path
return f"Successfully loaded video: {video_path}"
except Exception as e:
cap = None
return f"Error loading video: {str(e)}"
def get_next_video_frame():
"""
Get the next frame from the video.
Returns:
numpy array: Video frame
Raises:
RuntimeError: If video is not preloaded or frame cannot be read.
"""
global cap, frame_index
if cap is None:
raise RuntimeError("Video not preloaded. Call preload_video() first.")
ret, frame = cap.read()
if not ret:
# Loop the video
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
frame_index = 0
ret, frame = cap.read()
if not ret:
raise RuntimeError(f"Failed to read frame from video {current_video_path}.")
frame_index += 1
return frame
def reset_video_index():
"""
Reset the video frame index.
"""
global frame_index
frame_index = 0
if cap is not None:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
def release_video():
"""
Release the video capture object.
"""
global cap
if cap is not None:
cap.release()
cap = None