File size: 4,222 Bytes
b36e708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c39093b
b36e708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""
Script to extract frames from WebP files in data/shots/ and save them as png files in data/expanded/

Input:  data/shots/sample-XXX-Y.webp
Output: data/expanded/sample-XXX-Y-Z.png (where Z is the frame number starting from 0)
"""

import os
import sys
from pathlib import Path
from PIL import Image
import re


def extract_frames_from_webp(input_path, output_dir):
    """
    Extract all frames from a WebP file and save them as png files.
    
    Args:
        input_path (Path): Path to the input WebP file
        output_dir (Path): Directory to save the extracted frames
    
    Returns:
        int: Number of frames extracted
    """
    try:
        # Open the WebP file
        with Image.open(input_path) as img:
            # Parse filename to get sample and shot numbers
            filename = input_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 0
            
            sample_num = match.group(1)
            shot_num = match.group(2)
            
            frame_count = 0
            
            # Check if the image is animated (has multiple frames)
            try:
                while True:
                    # Convert to RGB if necessary (WebP can have transparency)
                    frame = img.convert('RGB')
                    
                    # Create output filename: sample-XXX-Y-Z.png
                    output_filename = f"sample-{sample_num}-{shot_num}-f{frame_count}.png"
                    output_path = output_dir / output_filename
                    
                    # Save the frame as PNG
                    frame.save(output_path)
                    print(f"Extracted frame {frame_count}: {output_filename}")
                    
                    frame_count += 1
                    
                    # Move to next frame
                    img.seek(img.tell() + 1)
                    
            except EOFError:
                # End of frames reached
                pass
            
            # If no frames were extracted (static image), extract the single frame
            if frame_count == 0:
                frame = img.convert('RGB')
                output_filename = f"sample-{sample_num}-{shot_num}-0.jpg"
                output_path = output_dir / output_filename
                frame.save(output_path, 'JPEG', quality=95)
                print(f"Extracted single frame: {output_filename}")
                frame_count = 1
            
            return frame_count
            
    except Exception as e:
        print(f"Error processing {input_path}: {e}")
        return 0


def main():
    """Main function to process all WebP files in data/shots/"""
    
    # Set up paths
    script_dir = Path(__file__).parent
    shots_dir = script_dir / "data" / "shots"
    expanded_dir = script_dir / "data" / "expanded"

    # Check if shots directory exists
    if not shots_dir.exists():
        print(f"Error: Shots directory not found: {shots_dir}")
        sys.exit(1)
    
    # Create expanded directory if it doesn't exist
    expanded_dir.mkdir(exist_ok=True)
    
    # Find all WebP files
    webp_files = list(shots_dir.glob('sample-193-*.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 to process")
    
    total_frames = 0
    processed_files = 0
    
    # Process each WebP file
    for webp_file in sorted(webp_files):
        print(f"\nProcessing: {webp_file.name}")
        frames_extracted = extract_frames_from_webp(webp_file, expanded_dir)
        
        if frames_extracted > 0:
            total_frames += frames_extracted
            processed_files += 1
        else:
            print(f"Failed to extract frames from {webp_file.name}")
    
    print(f"\n=== Summary ===")
    print(f"Processed files: {processed_files}/{len(webp_files)}")
    print(f"Total frames extracted: {total_frames}")
    print(f"Output directory: {expanded_dir}")


if __name__ == "__main__":
    main()