Tutorial Example

Python Capture Images From Video by Frames Using OpenCV: A Complete Guide

We can capture images by frames from video to analysis. In this tutorial, we will use python opencv to do it. You can learn how to do by our tutorial.

Install OpenCV

Before starting, we should install opencv for python. You can read tutorial below to start.

Install Python OpenCV on Windows 10 with Anaconda: A Complete Guide – OpenCV Tutorial

Import library

import cv2

Define a video file and a directory to save images

video = r'e:\vid.mp4'
video_images = 'e:\\video-images\\'

In this example, we will capture images from vid.mp4 and save images to e:\\video-images\\.

Create a VideoCapture object

cap = cv2.VideoCapture(video)
if not cap.isOpened():
    exit(0)

We can use VideoCapture object to get video frames and images.

Notice: the total frame count of video captured by opencv often is not correct. You can read this tutorial to learn more.

A Beginner Guide to Python Get Video Duration with OpenCV – Python Tutorial

Set to capture images per how many frames

#Capture images per 25 frame
frameFrequency=25

In this example, we will capture images per 25 frames.

Capture images from video

#iterate all frames
total_frame = 0
id = 0
while True:
    ret, frame = cap.read()
    if ret is False:
        break
    total_frame += 1
    if total_frame%frameFrequency == 0:
        id += 1
        image_name = video_images + str(id) +'.jpg'
        cv2.imwrite(image_name, frame)
        print(image_name)
    
cap.release()

Code above will captrue images from video.

The images are: