In this post we extract a image at a particular time from a video using the Python OpenCV library.
Steps
- Import OpenCV library
- Read the video file using cv2.VideoCapture().
- Set the video position to a particular (say 2 seconds) time using vid.set(cv2.CAP_PROP_POS_MSEC,2000).
- Read the frame at the set position using vid.read().
- Save the frame as an image using cv2.imwrite().
- Finally check if the image is successfully saved or not.
Complete Program
In the program below, we extract an image at 2 seconds or 2,000 milliseconds time from a video.
import cv2#Read the videovid = cv2.VideoCapture(r"C:\Users\Public\Videos\Sample Videos\Wildlife.wmv")# Go to 2 Second Position (2 Sec = 2,000 milliseconds)vid.set(cv2.CAP_PROP_POS_MSEC,2000)# Retrieve the frame as an imagesuccess,image = vid.read()while success:time = vid.get(cv2.CAP_PROP_POS_MSEC)ret = cv2.imwrite("frame2sec.jpg", image) # save frame as JPEG fileif ret:print("image is saved successfully at time: ", time)break
Output
image is saved successfully at time: 2035.0000000000002
Program Explanation
We read the video using cv2.VideoCapture(). For this we need to create an object of VideoCapture class. We created vid, an object of this class.
After creating the VideoCapture object, we set the position of the video passing the flag CAP_PROP_POS_MSEC and it's value as 2,000. Here we set position to 2 seconds that is 2,000 milliseconds.
Next we applied read() method to read the frame. This method returns the next frame of the video. Please notice in the output, we have specified 2,000 milliseconds but it returns the frame at 2035.0000000000002 milliseconds. This method also returns true or false, true if frame successfully read else false.
If the frame is successfully read, we save the frame as a jpeg image using cv2.imwrite() method. It returns true if the frame is successfully saved.
We also compute the frame time using cv2.get() with the same flag CAP_PROP_POS_MSEC.
Finally we print the message of successfully saved frame/ image.
Further Reading:
- How to Load and Visualize Multiple Images in Python
- Mathematical Operations On Images Using OpenCV and NumPy in Python
- Basic Operations on Images using OpenCV in Python
- Different ways to load images in Python
- How to compute mean, standard deviation, and variance of a tensor in PyTorch
- How to calculate mean and standard deviation of images in PyTorch
- How to normalize image dataset in PyTorch
Useful Resources:
Comments
Post a Comment