How to locally extract and save individual frames from a video?

Videos can be a useful source of training data for any type of computer vision model. Especially if you are planning to deploy your computer vision models in a video context, having similar training data as your deployment environment can help improve performance.

There are two separate ways to extract and save frames for a video file.

If you are looking to directly train a computer vision model, you can upload it directly to Roboflow so you can export, train, and deploy your models easily.

Alternatively, you can also extract video frames, save them and upload them to Roboflow by using Supervision. Here’s how:

# First, create a directory to save your video frames
import os

FRAMES_DIR = "/content/frames"
os.mkdir(FRAMES_DIR)
# Then, you can use Supervision's get_video_frames_generator function
import supervision as sv
from PIL import Image

frames_generator = sv.get_video_frames_generator(VIDEO_PATH)

for i, frame in enumerate(frames_generator):
  img = Image.fromarray(frame)
  img.save(f"{FRAMES_DIR}/video_frame{i}.jpg")

print(f"Saved frames to {FRAMES_DIR}")

For more options, such as controlling the start/stop and frame sampling, learn more about Supervision’s get_video_frames_generator function here