sprite-dx-data / random_frame_extractor.py
Candle
random data
c39093b
#!/usr/bin/env python3
"""
Script to randomly extract k frames from WebP files in data/shots/ and save them as PNG files.
Usage:
python random_frame_extractor.py <k> <output_dir>
Where:
k: Number of frames to extract
output_dir: Directory to save the extracted frames
Input: data/shots/sample-XXX-Y.webp (randomly selected)
Output: <output_dir>/sample-XXX-Y-fZ.png (where Z is the frame number, e.g., f20 for frame 20)
"""
import os
import sys
import random
from pathlib import Path
from PIL import Image
import re
import argparse
def get_frame_count(webp_path):
"""
Get the total number of frames in a WebP file.
Args:
webp_path (Path): Path to the WebP file
Returns:
int: Number of frames in the file
"""
try:
with Image.open(webp_path) as img:
frame_count = 0
try:
while True:
img.seek(frame_count)
frame_count += 1
except EOFError:
pass
return max(1, frame_count) # At least 1 frame for static images
except Exception as e:
print(f"Error reading {webp_path}: {e}")
return 0
def extract_random_frames(webp_path, output_dir, num_frames_to_extract):
"""
Extract random frames from a WebP file and save them as PNG files.
Args:
webp_path (Path): Path to the input WebP file
output_dir (Path): Directory to save the extracted frames
num_frames_to_extract (int): Number of frames to extract from this file
Returns:
list: List of extracted frame filenames
"""
try:
# Parse filename to get sample and shot numbers
filename = webp_path.stem # e.g., "sample-123-2"
match = re.match(r'sample-(\d+)-(\d+)', filename)
if not match:
print(f"Warning: Filename {filename} doesn't match expected pattern")
return []
sample_num = match.group(1)
shot_num = match.group(2)
# Get total frame count
total_frames = get_frame_count(webp_path)
if total_frames == 0:
return []
# Determine how many frames to extract (don't exceed available frames)
frames_to_extract = min(num_frames_to_extract, total_frames)
# Select random frame indices
if total_frames == 1:
selected_frames = [0]
else:
selected_frames = sorted(random.sample(range(total_frames), frames_to_extract))
extracted_files = []
with Image.open(webp_path) as img:
for frame_idx in selected_frames:
try:
# Seek to the specific frame
img.seek(frame_idx)
# Convert to RGB if necessary
frame = img.convert('RGB')
# Create output filename: sample-XXX-Y-fZ.png
output_filename = f"sample-{sample_num}-{shot_num}-f{frame_idx}.png"
output_path = output_dir / output_filename
# Save the frame as PNG
frame.save(output_path)
extracted_files.append(output_filename)
print(f"Extracted frame {frame_idx} from {webp_path.name}: {output_filename}")
except Exception as e:
print(f"Error extracting frame {frame_idx} from {webp_path}: {e}")
return extracted_files
except Exception as e:
print(f"Error processing {webp_path}: {e}")
return []
def main():
"""Main function to randomly extract k frames from WebP files"""
# Parse command line arguments
parser = argparse.ArgumentParser(description='Randomly extract k frames from WebP files')
parser.add_argument('k', type=int, help='Number of frames to extract')
parser.add_argument('output_dir', type=str, help='Output directory for extracted frames')
parser.add_argument('--frames-per-file', type=int, default=3,
help='Maximum frames to extract per WebP file (default: 3)')
parser.add_argument('--seed', type=int, help='Random seed for reproducible results')
args = parser.parse_args()
if args.k <= 0:
print("Error: k must be a positive integer")
sys.exit(1)
# Set random seed if provided
if args.seed is not None:
random.seed(args.seed)
print(f"Using random seed: {args.seed}")
# Set up paths
script_dir = Path(__file__).parent
shots_dir = script_dir / "data" / "shots"
output_dir = Path(args.output_dir)
# Check if shots directory exists
if not shots_dir.exists():
print(f"Error: Shots directory not found: {shots_dir}")
sys.exit(1)
# Create output directory if it doesn't exist
output_dir.mkdir(parents=True, exist_ok=True)
print(f"Output directory: {output_dir}")
# Find all WebP files
webp_files = list(shots_dir.glob('sample-*.webp'))
if not webp_files:
print(f"No WebP files found in {shots_dir}")
sys.exit(1)
print(f"Found {len(webp_files)} WebP files available")
# Calculate how many files we need to process
frames_per_file = args.frames_per_file
files_needed = (args.k + frames_per_file - 1) // frames_per_file # Ceiling division
files_needed = min(files_needed, len(webp_files))
# Randomly select WebP files
selected_files = random.sample(webp_files, files_needed)
print(f"Randomly selected {len(selected_files)} WebP files")
total_extracted = 0
extracted_files = []
# Process each selected WebP file
for i, webp_file in enumerate(selected_files):
remaining_frames = args.k - total_extracted
if remaining_frames <= 0:
break
# Calculate how many frames to extract from this file
frames_from_this_file = min(frames_per_file, remaining_frames)
print(f"\nProcessing ({i+1}/{len(selected_files)}): {webp_file.name}")
print(f"Extracting up to {frames_from_this_file} frames...")
files = extract_random_frames(webp_file, output_dir, frames_from_this_file)
extracted_files.extend(files)
total_extracted += len(files)
print(f"\n=== Summary ===")
print(f"Target frames: {args.k}")
print(f"Frames extracted: {total_extracted}")
print(f"Files processed: {len(selected_files)}")
print(f"Output directory: {output_dir}")
if total_extracted < args.k:
print(f"Warning: Only extracted {total_extracted} frames out of {args.k} requested")
print(f"\nExtracted files:")
for filename in extracted_files:
print(f" {filename}")
if __name__ == "__main__":
main()