Hi everyone, in the below given code I want to automate the video_start_time to capture the start time directly from the first frame of the video and I am unable to do it.
import cv2
import os
from datetime import datetime
def hms_to_seconds(hms):
“”“Convert hh:mm:ss string to seconds.”“”
h, m, s = map(int, hms.split(“:”))
return h * 3600 + m * 60 + s
def calculate_offset_seconds(start_time, program_time):
“”“Return the number of seconds between program_time and start_time.”“”
fmt = “%H:%M:%S”
t1 = datetime.strptime(start_time, fmt)
t2 = datetime.strptime(program_time, fmt)
delta = (t2 - t1).total_seconds()
return int(delta)
def capture_screenshots(video_path, program_timestamps, video_start_time, output_dir=“screenshots”):
“”"
Capture screenshots from a video at program timestamps.
:param video_path: Path to the .mp4 file
:param program_timestamps: List of program times (e.g., ["19:01:30"])
:param video_start_time: The actual start time of the video (e.g., "19:00:01")
:param output_dir: Folder to save screenshots
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(" Error opening video file.")
return
fps = cap.get(cv2.CAP_PROP_FPS)
for i, prog_time in enumerate(program_timestamps):
seconds_offset = calculate_offset_seconds(video_start_time, prog_time)
frame_number = int(fps * seconds_offset)
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
success, frame = cap.read()
if success:
filename = os.path.join(output_dir, f"screenshot_{i+1}_{prog_time.replace(':', '-')}.png")
cv2.imwrite(filename, frame)
print(f" Saved: {filename}")
else:
print(f" Failed to capture frame at program time {prog_time}.")
cap.release()
if name == “main”:
video_file = “1010013_2024-07-22_19-00-01.Mp4”
# Real broadcast start time of the video
video_start_time = "19:00:00" # Match this with the actual time the program started
# These are timestamps shown during the broadcast on screen
program_timestamps = [
# "19:04:32",
# "19:05:00",
# "19:26:16",
# "19:28:06",
# "19:29:16",
]
capture_screenshots(video_file, program_timestamps, video_start_time)