You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python中不使用OpenCV从25FPS播放视频中每秒捕获25帧

Solution: Capture 25 Frames Per Second from a 25FPS Video (No OpenCV)

Got it, let's tackle this problem—since your video runs at 25FPS, capturing every single frame means we need to extract all frames without skipping any. Here are two reliable Python-based approaches that don't rely on OpenCV:

Approach 1: Use ffpyplayer (Python FFmpeg Binding)

ffpyplayer is a lightweight Python library built on FFmpeg, perfect for video frame extraction without OpenCV.

Step 1: Install the Library

First, install it via pip:

pip install ffpyplayer

Step 2: Full Implementation Code

from ffpyplayer.player import MediaPlayer
import numpy as np
import os
from PIL import Image

def extract_all_frames(video_path, output_dir):
    # Initialize media player
    player = MediaPlayer(video_path)
    frame_count = 0
    
    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)
    
    while True:
        # Get next frame and timestamp
        frame, val = player.get_frame()
        
        if val == 'eof':
            # End of video
            break
        if frame is None:
            # Wait for the next frame (handle buffering)
            continue
        
        # Convert frame to numpy array for processing or saving
        img, _ = frame
        frame_np = np.array(img.to_bytearray()[0]).reshape(img.get_size()[1], img.get_size()[0], 3)
        
        # Save the frame as a JPG file
        img_pil = Image.fromarray(frame_np)
        img_pil.save(f"{output_dir}/frame_{frame_count:04d}.jpg")
        
        frame_count += 1
        print(f"Captured frame {frame_count}", end='\r')
    
    print(f"\nDone! Captured {frame_count} frames total.")
    player.close()

# Example usage
extract_all_frames("your_video.mp4", "captured_frames")

Notes:

  • This code saves each frame as a JPG in the specified directory. If you don't need to save frames and just want to process them in-memory, skip the PIL saving step.
  • The get_frame() method ensures we pull frames in sequence, perfectly matching the video's 25FPS rate.

Approach 2: Call FFmpeg Directly via subprocess

If you have FFmpeg installed on your system (most OSes can install it easily), using the command line via Python's subprocess module is often faster and more efficient.

Step 1: Ensure FFmpeg is Installed

Check if FFmpeg is available by running ffmpeg -version in your terminal. If not, install it via your package manager (e.g., sudo apt install ffmpeg on Ubuntu, brew install ffmpeg on macOS, or grab the official build for Windows).

Step 2: Python Implementation

import subprocess
import os

def extract_all_frames_ffmpeg(video_path, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    
    # FFmpeg command to extract every frame at 25FPS
    # %04d ensures frames are numbered with 4 digits (0001, 0002, etc.)
    cmd = [
        "ffmpeg",
        "-i", video_path,
        "-vf", "fps=25",  # Explicitly match the video's frame rate
        "-q:v", "1",  # High output quality (lower number = better quality)
        f"{output_dir}/frame_%04d.jpg"
    ]
    
    # Run the command and handle output
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        print("Successfully extracted all frames!")
    else:
        print(f"Error occurred: {result.stderr}")

# Example usage
extract_all_frames_ffmpeg("your_video.mp4", "captured_frames_ffmpeg")

Notes:

  • The -vf fps=25 flag guarantees we extract exactly 25 frames per second, which for your 25FPS video means grabbing every single frame.
  • Adjust the -q:v parameter to tweak output quality (1 = best, 31 = worst) based on your needs.

内容的提问来源于stack exchange,提问作者Surenthar

火山引擎 最新活动