Extract images from video in Python
Prerequisites
- Python 3.x
- OpenCV library for Python
Reading a Video File
First, we need to read the video file using the cv2.VideoCapture()
function. This function returns a VideoCapture
object, which we can use to read the frames of the video.
import cv2
# Open the video file
video = cv2.VideoCapture('video.mp4')
Extracting Frames from the Video
To extract the frames from the video, we can use a while
loop and the VideoCapture.read()
method. This method returns a tuple containing a boolean value indicating whether the frame was successfully read and the frame itself.
# Read the frames from the video
while True:
# Read the next frame
success, frame = video.read()
# Check if we reached the end of the video
if not success:
break
# Do something with the frame
# ...
Saving the Frames as Images
To save the frames as images, we can use the cv2.imwrite()
function. This function takes the file name and the image as arguments and saves the image to the specified file.
# Save the frame to an image file
cv2.imwrite('frame.jpg', frame)
Extracting Frames at a Specific Frame Rate
By default, the VideoCapture.read()
method reads the frames of the video at the original frame rate. However, we can specify a different frame rate by using the VideoCapture.set()
method to set the cv2.CAP_PROP_FPS
property.
For example, to extract one frame per second from the video, we can use the following code:
# Set the frame rate to 1 frame per second
video.set(cv2.CAP_PROP_FPS, 1)
Putting It All Together
Here is the complete code for extracting frames from a video and saving them as images:
import cv2
# Open the video file
video = cv2.VideoCapture('video.mp4')
# Set the frame rate to 1 frame per second
video.set(cv2.CAP_PROP_FPS, 1)
# Set the starting frame
frame_number = 0
# Read the frames from the video
while True:
# Read the next frame
success, frame = video.read()
# Check if we reached the end of the video
if not success:
break
# Save the frame to an image file
cv2.imwrite(f'frame_{frame_number}.jpg', frame)
# Increment the frame number
frame_number += 1
# Release the video capture object
video.release()
This code reads the frames of the video one by one, saves each frame to an image file with a name like frame_0.jpg
, frame_1.jpg
, and so on, and increments the frame number
Leave a Comment