Spaces:
Sleeping
Sleeping
File size: 2,642 Bytes
0d9760b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | # KeyFrameSelection/FeatureExtraction.py
import os
import csv
import pandas as pd
import av
import cv2
def _get_timestamp(frame_idx, fps):
"""
Converts a frame index to a formatted timestamp string (HH:MM:SS.mmm).
Args:
frame_idx (int): Index of the frame in the video.
fps (float): Frames per second of the video.
Returns:
str: Timestamp in the format 'HH:MM:SS.mmm' representing the frame time.
"""
seconds = frame_idx / fps
h = int(seconds // 3600)
m = int((seconds % 3600) // 60)
s = int(seconds % 60)
ms = int((seconds - int(seconds)) * 1000)
return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"
def process_video(video_path, interval_sec=3):
"""
Samples frames from a video at fixed time intervals.
Args:
video_path (str): Path to the input video file.
interval_sec (int, optional): Time interval in seconds between sampled frames. Defaults to 3.
Returns:
tuple:
- records (list): List of tuples (frame, frame_idx) for each sampled frame.
- fps (float): Frames per second of the input video.
"""
container = av.open(video_path)
stream = container.streams.video[0]
fps = float(stream.average_rate)
interval = int(fps * interval_sec)
records = []
for i, frame in enumerate(container.decode(video=0)):
if i % interval == 0:
img = frame.to_ndarray(format="bgr24")
records.append((img, i))
return records, fps
def save_records(records, output_dir, output_csv, fps):
"""
Saves filtered keyframes to disk and writes their metadata (path and timestamp) to a CSV file.
Args:
records (list): List of tuples (frame, frame_idx) to be saved.
output_dir (str): Directory where the keyframe images will be stored.
output_csv (str): Path to the output CSV file to store keyframe paths and timestamps.
fps (float): Frames per second of the original video, used to calculate timestamps.
Returns:
pandas.DataFrame: DataFrame containing the saved keyframe paths and their corresponding timestamps.
"""
os.makedirs(output_dir, exist_ok=True)
rows = []
for i, (frame, frame_idx) in enumerate(records):
frame_name = f"keyframe_{i:04d}.jpg"
out_path = os.path.join(output_dir, frame_name)
cv2.imwrite(out_path, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
timestamp = _get_timestamp(frame_idx, fps)
rows.append([out_path, timestamp])
df = pd.DataFrame(rows, columns=["keyframe", "timestamp"])
df.to_csv(output_csv, index=False)
return df
|