0
0
Computer Visionml~5 mins

Frame extraction in Computer Vision

Choose your learning style9 modes available
Introduction
Frame extraction helps us take pictures from a video so we can look at or use them separately.
You want to analyze a video by looking at individual pictures.
You need to create a photo gallery from a video clip.
You want to detect objects or faces in specific moments of a video.
You want to make a time-lapse or summary from a long video.
You want to prepare images for training a machine learning model.
Syntax
Computer Vision
import cv2

cap = cv2.VideoCapture('video.mp4')

success, frame = cap.read()
if success:
    cv2.imwrite('frame.jpg', frame)
cap.release()
cv2.VideoCapture opens the video file or camera stream.
cap.read() reads one frame at a time; success tells if reading worked.
Examples
Extracts the 10th frame from the video and saves it as an image.
Computer Vision
import cv2

cap = cv2.VideoCapture('video.mp4')

frame_number = 10
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
success, frame = cap.read()
if success:
    cv2.imwrite('frame10.jpg', frame)
cap.release()
Extracts every 30th frame from the video and saves it as an image.
Computer Vision
import cv2

cap = cv2.VideoCapture('video.mp4')
count = 0
while True:
    success, frame = cap.read()
    if not success:
        break
    if count % 30 == 0:
        cv2.imwrite(f'frame_{count}.jpg', frame)
    count += 1
cap.release()
Sample Model
This program opens a video file, extracts the first frame, saves it as an image, and prints a confirmation message.
Computer Vision
import cv2

# Open the video file
cap = cv2.VideoCapture('sample_video.mp4')

# Check if video opened successfully
if not cap.isOpened():
    print('Error: Cannot open video file')
    exit()

# Read the first frame
success, frame = cap.read()

if success:
    # Save the first frame as an image
    cv2.imwrite('first_frame.jpg', frame)
    print('First frame extracted and saved as first_frame.jpg')
else:
    print('Error: Cannot read frame')

cap.release()
OutputSuccess
Important Notes
Always release the video capture object with cap.release() to free resources.
Frame numbering starts at 0, so the first frame is frame 0.
If the video file path is wrong or the file is corrupted, reading frames will fail.
Summary
Frame extraction means taking pictures from a video one by one.
Use OpenCV's VideoCapture and read() to get frames.
Save frames as images to use them for analysis or display.