-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_video_resized.py
More file actions
170 lines (134 loc) · 5.26 KB
/
create_video_resized.py
File metadata and controls
170 lines (134 loc) · 5.26 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python3
"""
Create Video with Resized Images
Resizes the processed images to a manageable size and creates a video.
"""
import os
import sys
import subprocess
from pathlib import Path
from PIL import Image
def resize_images_for_video(input_dir="output", resized_dir="resized", target_width=1920):
"""Resize images to a manageable size for video creation"""
print(f"Resizing images to {target_width}px width for video...")
input_path = Path(input_dir)
resized_path = Path(resized_dir)
resized_path.mkdir(exist_ok=True)
# Get all bitmap files
image_files = sorted(list(input_path.glob("*.bmp")))
if not image_files:
print(f"No images found in {input_dir}")
return False
print(f"Found {len(image_files)} images to resize...")
for i, image_file in enumerate(image_files):
try:
if i % 50 == 0:
print(f"Resizing image {i+1}/{len(image_files)}...")
# Open and resize image
with Image.open(image_file) as img:
# Calculate new height maintaining aspect ratio
aspect_ratio = img.height / img.width
new_height = int(target_width * aspect_ratio)
# Resize image
resized_img = img.resize((target_width, new_height), Image.Resampling.LANCZOS)
# Save resized image
output_filename = image_file.name
output_path = resized_path / output_filename
resized_img.save(output_path, 'BMP')
except Exception as e:
print(f"Error resizing {image_file.name}: {e}")
return False
print(f"✓ Resized {len(image_files)} images to {target_width}x{new_height}")
return True
def create_video_from_resized(resized_dir="resized", video_dir="video", fps=60):
"""Create video from resized images"""
print(f"Creating {fps}fps video from resized images...")
resized_path = Path(resized_dir)
video_path = Path(video_dir)
video_path.mkdir(exist_ok=True)
# Get resized images
image_files = sorted(list(resized_path.glob("*.bmp")))
if not image_files:
print(f"No resized images found in {resized_dir}")
return False
print(f"Found {len(image_files)} resized images...")
# Create video filename
base_name = image_files[0].stem.split('_video_echo_')[0]
video_filename = f"{base_name}_echo_progression_{fps}fps_resized.mp4"
video_file = video_path / video_filename
# Build FFmpeg command
input_pattern = str(resized_path / f"{base_name}_video_echo_%04d.bmp")
cmd = [
"ffmpeg",
"-y",
"-framerate", str(fps),
"-i", input_pattern,
"-c:v", "libx264",
"-preset", "fast",
"-crf", "23",
"-pix_fmt", "yuv420p",
str(video_file)
]
print(f"Creating video: {video_filename}")
print(f"Command: {' '.join(cmd)}")
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
print(f"✓ Video created successfully: {video_filename}")
# Get video info
info_cmd = ["ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", str(video_file)]
info_result = subprocess.run(info_cmd, capture_output=True, text=True, check=True)
import json
info = json.loads(info_result.stdout)
duration = float(info['format']['duration'])
print(f"✓ Video duration: {duration:.2f} seconds")
print(f"✓ Frame count: {len(image_files)} frames")
print(f"✓ Video saved to: {video_file}")
return True
except subprocess.CalledProcessError as e:
print(f"✗ Error creating video: {e.stderr}")
return False
def main():
"""Main function"""
# Default parameters
target_width = 1920 # 1080p width
fps = 60
# Allow command line arguments
if len(sys.argv) > 1:
try:
target_width = int(sys.argv[1])
if target_width < 480 or target_width > 3840:
print("Target width should be between 480 and 3840")
return
except ValueError:
print("Please provide a valid number for target width")
return
if len(sys.argv) > 2:
try:
fps = int(sys.argv[2])
if fps < 1 or fps > 120:
print("FPS should be between 1 and 120")
return
except ValueError:
print("Please provide a valid number for FPS")
return
print("Starting video creation with resized images...")
print("=" * 60)
print(f"Target width: {target_width}px")
print(f"FPS: {fps}")
print("=" * 60)
# Step 1: Resize images
if not resize_images_for_video(target_width=target_width):
print("Failed to resize images")
return
print()
# Step 2: Create video
if not create_video_from_resized(fps=fps):
print("Failed to create video")
return
print()
print("=" * 60)
print("Video creation completed successfully!")
print("=" * 60)
if __name__ == "__main__":
main()