Timestamps provide a virtual timeline in a sequence of scenes captured from an aerial drone video and it is highly relevant when there are multiple tours.
For example, the following code demonstrates how to correlate timestamps from extracted frames without doing indexing by leveraging sequence in frames from the video. Indexing of video is already demonstrated in the references in the previous articles.
import cv2
import os
def format_timestamp(seconds):
# Format seconds into HH:MM:SS.mmm
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02}:{minutes:02}:{secs:02}.{millis:03}"
def extract_key_frames(video_path, output_dir, num_frames=5):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise IOError(f"Cannot open video file: {video_path}")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
duration_sec = total_frames / fps
print(f"Video FPS: {fps}")
print(f"Total frames: {total_frames}")
print(f"Duration: {duration_sec:.3f} seconds")
step = total_frames // num_frames
frame_indices = [i * step for i in range(num_frames)]
os.makedirs(output_dir, exist_ok=True)
timestamps = []
for idx, frame_no in enumerate(frame_indices):
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
ret, frame = cap.read()
if not ret:
print(f"Warning: Could not read frame {frame_no}")
continue
frame_filename = os.path.join(output_dir, f"frame_{idx+1}.jpg")
cv2.imwrite(frame_filename, frame)
timestamp_sec = frame_no / fps
timestamp = format_timestamp(timestamp_sec)
timestamps.append((frame_filename, timestamp))
cap.release()
return timestamps
# Example usage
video_file = "videosummary01.mp4"
output_folder = "extracted_frames"
frame_data = extract_key_frames(video_file, output_folder, num_frames=5)
print("\nExtracted Frame Timestamps:")
for fname, ts in frame_data:
print(f"{fname} -> {ts}")
Output:
Video FPS: 25.08108108108108
Total frames: 27
Duration: 1.077 seconds
Extracted Frame Timestamps:
extracted_frames\frame_1.jpg -> 00:00:00.000
extracted_frames\frame_2.jpg -> 00:00:00.199
extracted_frames\frame_3.jpg -> 00:00:00.398
extracted_frames\frame_4.jpg -> 00:00:00.598
extracted_frames\frame_5.jpg -> 00:00:00.797