如何为Python Pygame四维立方体程序输出指定时长MP4?
Hey there! Let's break down two solid ways to record your rotating ASCII tesseract into an MP4 video—both options you considered work great, and I'll show you exactly how to plug them into your existing code.
Option 1: Save Frames as Images + Convert with FFmpeg
This is a straightforward approach, especially if you don't want to mess with extra Python libraries beyond what you already have. You'll need FFmpeg installed on your system (it's a free, open-source tool for video processing).
Step-by-Step Implementation:
- Create a temporary folder to store frames (we'll clean it up later if you want).
- Modify your Pygame loop to save each frame as a PNG file.
- Use FFmpeg to convert the sequence of images into an MP4.
Modified Code Snippets:
First, add these imports at the top:
import subprocess import shutil
Then, before your main loop, set up the frame directory and frame counter:
# Video recording settings record_duration = 30 # seconds (adjust to 60 for 1 minute) total_frames = record_duration * fps frame_counter = 0 frame_dir = "tesseract_frames" # Create frame directory if it doesn't exist os.makedirs(frame_dir, exist_ok=True)
Inside your main loop, right after pygame.display.update(), add code to save frames until we hit the total needed:
pygame.display.update() # Save frame if we're still recording if frame_counter < total_frames: frame_path = os.path.join(frame_dir, f"frame_{frame_counter:04d}.png") pygame.image.save(screen, frame_path) frame_counter += 1 else: # Stop recording once we hit the desired duration run = False
After the loop ends, add code to convert frames to MP4 with FFmpeg:
pygame.quit() # Convert frames to MP4 using FFmpeg ffmpeg_cmd = [ "ffmpeg", "-framerate", str(fps), "-i", os.path.join(frame_dir, "frame_%04d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "tesseract_video.mp4" ] subprocess.run(ffmpeg_cmd, check=True) # Optional: Delete the frame directory to save space shutil.rmtree(frame_dir)
Option 2: Record Directly with OpenCV (cv2)
If you prefer to avoid saving tons of image files, OpenCV can write frames directly to an MP4 file in memory. This requires installing the opencv-python package.
Step-by-Step Implementation:
- Install OpenCV: Run
pip install opencv-pythonin your terminal. - Set up a VideoWriter object before your loop.
- Convert each Pygame frame to a format OpenCV understands and write it to the video.
Modified Code Snippets:
Add this import at the top:
import cv2 import numpy as np
Before your main loop, set up the VideoWriter:
# Video recording settings record_duration = 30 # seconds (adjust to 60 for 1 minute) total_frames = record_duration * fps frame_counter = 0 # Set up OpenCV VideoWriter video_width, video_height = width, height fourcc = cv2.VideoWriter_fourcc(*'mp4v') # MP4 codec video_writer = cv2.VideoWriter('tesseract_video.mp4', fourcc, fps, (video_width, video_height))
Inside your main loop, right after pygame.display.update(), add:
pygame.display.update() # Write frame to video if we're still recording if frame_counter < total_frames: # Convert Pygame surface to OpenCV format frame = pygame.surfarray.array3d(screen) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # OpenCV uses BGR instead of RGB video_writer.write(frame) frame_counter += 1 else: run = False
After the loop ends, release the VideoWriter:
pygame.quit() # Release OpenCV resources video_writer.release()
Quick Notes for Beginners:
- FFmpeg Installation: If you don't have FFmpeg, download it from the official site and add it to your system PATH so the command works from any terminal.
- MoviePy Troubleshooting: If you still want to try MoviePy, make sure you installed it correctly (
pip install moviepy) and that you have FFmpeg installed (MoviePy uses it under the hood). But the two options above are simpler for a beginner! - Performance: Recording might slow down your animation a bit—if that happens, you can lower the
fpsslightly or use a smaller window size temporarily.
内容的提问来源于stack exchange,提问作者pelpa

