Save still images from camera video with OpenCV in Python

Posted: | Tags: Python, OpenCV

This article describes how to capture still images from a video (live stream) of a camera (built-in camera, USB camera, or webcam) and save it as an image file with OpenCV in Python.

The following sample code is shown here.

  • Save an image when a keyboard is pressed
  • Save images at given intervals

See the following article for information on how to save a still image from a video file instead of a live stream from a camera.

See the following article for basic information on how to handle video in OpenCV.

Save an image when a keyboard is pressed

The following is a sample code that displays the video from the camera in real time and saves the frame as an image file when the keyboard is pressed.

Press q to exit and c to save the image in the specified directory with the file name of <basename>_<number>.<extension>.

import cv2
import os


def save_frame_camera_key(device_num, dir_path, basename, ext='jpg', delay=1, window_name='frame'):
    cap = cv2.VideoCapture(device_num)

    if not cap.isOpened():
        return

    os.makedirs(dir_path, exist_ok=True)
    base_path = os.path.join(dir_path, basename)

    n = 0
    while True:
        ret, frame = cap.read()
        cv2.imshow(window_name, frame)
        key = cv2.waitKey(delay) & 0xFF
        if key == ord('c'):
            cv2.imwrite('{}_{}.{}'.format(base_path, n, ext), frame)
            n += 1
        elif key == ord('q'):
            break

    cv2.destroyWindow(window_name)


save_frame_camera_key(0, 'data/temp', 'camera_capture')

See the following article for a sample code to play video from a camera.

Create a directory with os.makedirs().

You can join path strings with os.path.join().

In this example, a number that increases with each press of c is appended to the file name. If you want to append date and time information, you can use the datetime module of the standard library. The following example uses datetime.

Save images at given intervals

The following is a sample code that captures video from a camera at given intervals and saves it as an image file.

Images are saved in the specified directory with the file name of <basename>_<timestamp>.<extension>.

import cv2
import os
import datetime


def save_frame_camera_cycle(device_num, dir_path, basename, cycle, ext='jpg', delay=1, window_name='frame'):
    cap = cv2.VideoCapture(device_num)

    if not cap.isOpened():
        return

    os.makedirs(dir_path, exist_ok=True)
    base_path = os.path.join(dir_path, basename)

    n = 0
    while True:
        ret, frame = cap.read()
        cv2.imshow(window_name, frame)
        if cv2.waitKey(delay) & 0xFF == ord('q'):
            break
        if n == cycle:
            n = 0
            cv2.imwrite('{}_{}.{}'.format(base_path, datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'), ext), frame)
        n += 1

    cv2.destroyWindow(window_name)


save_frame_camera_cycle(0, 'data/temp', 'camera_capture_cycle', 300)

The code is almost the same as the keyboard example above.

You can change the timestamp format with a format string specified to strftime(). The isoformat() method, which returns a string in ISO format, is also provided.

The frames displayed by OpenCV are counted. If the image is displayed at about 30FPS, for example, the image is saved every 10 seconds with cycle=300.

Note that if the variable cycle, which specifies the cycle of frames to be saved, is set to a small value, many images would be saved.

Related Categories

Related Articles