Extracting Frames from a Video and Saving them as Images using OpenCV in Python

This post provides a Python code example for extracting frames from a video and saving them as images using the OpenCV library. The code uses a loop to process each frame in the video, saves the frames to a directory, and displays them in a window.

Let us look at an example to read a video file, display the frames one by one and then save them in a folder:

Code 1-1 Read a video, extract frames, display them and then save them in a folder.
 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
import cv2
import os

directory = 'D:\\img\\videos\\'
filename = 'walking.avi'
path = directory +filename

# Open a video file
cap = cv2.VideoCapture(path)

destination = directory + "frames\\"
# Create a directory to store frames
if not os.path.exists(destination):
    os.makedirs(destination)

# Loop through the video frames
frame_count = 0
while cap.isOpened():
    # Read a frame from the video
    ret, frame = cap.read()
    
    # Check if the frame was successfully read
    if not ret:
        break
    
    # Save the frame to a file
    frame_count += 1
    filename = f"frame{frame_count:04}.jpg"
    filepath = os.path.join(destination, filename)
    cv2.imwrite(filepath, frame)
    
    # Display the frame
    cv2.imshow("Frame", frame)
    
    # Wait for a key event
    if cv2.waitKey(1) == ord('q'):
        break
# Release the video capture and destroy all windows
cap.release()
cv2.destroyAllWindows()


Line 1-2: We start with importing required packages.
Line 4-6: Define the video file name and video path to read.
Line 9: Open a video file using the cv2.VideoCapture() function
Line 11- 14: Define the destination folder where the frames will be written. Create a directory called "frames" at the destination location to store the extracted frames using the os.makedirs() function if it does not exists.
Line 18: Start a loop to process each frame in the video one by one.
Line 20: Read a frame from the video using the cap.read() function.
Line 23-24: Check if the frame was successfully read using the ret variable. If it's False, we've reached the end of the video and we break out of the loop.
Line 27-30: Save the frame to a file in the "frames" directory using the cv2.imwrite() function. We use a frame counter variable to keep track of the frame number and create a filename with a 4-digit zero-padded frame number.
Line 33:Display the frame using the cv2.imshow() function.
Line 36-37: Wait for a key event using the cv2.waitKey() function. We wait for 1 millisecond and check if the user has pressed the 'q' key. If they have, we break out of the loop.
Line 39-40: Release the video capture using the cap.release() function and destroy all windows using the cv2.destroyAllWindows() function.

This code will extract all frames from the input video and save them to a directory called "frames". The frame files will be named "frame0001.jpg", "frame0002.jpg", and so on. The code also displays each frame in a window and waits for the user to press the 'q' key to quit.

No image
Figure 1: Extracted frames from video are stored in Frames folder.

OpenCV Tutorials