Extract image from video at given time using OpenCV in Python
In this post, we will learn how to extract images from the video at a given time in Python using OpenCV. OpenCV is an open-source package that allows us to work on video, images, and frames. This tool also allows us to deep dive into artificial intelligence, machine learning, and computer vision. Extracting images from a video allows for a better understanding of the frames that are offered in it.
Extract image from video: When the time is pre-defined
Be sure to install OpenCV to your system by following the pip install
pip install opencv-python. After that, import it into your code by writing
import cv2. Now, you are one step ahead to extract images from a video using OpenCV.
import cv2 #taking the input video_capture = cv2.VideoCapture('d:/video.mp4') #setting the time video_capture.set(cv2.CAP_PROP_POS_MSEC,37000) success,image = video_capture.read() if success: cv2.imwrite("frame37sec.jpg", image) cv2.imshow("37sec",image) cv2.waitKey()
Explanation when the time is pre-defined:
- Importing the OpenCV library (Line 1).
- The variable video_capture stores the path of the video, from which we can extract frames (Line 4).
- The set() function allows us to specify the time for which the frame we want. (Line 7).
- The boolean value (Line 9) represents success.
- If success is true, then imwrite() takes the name of the frame (Line 12).
- im.show() takes the name of the pop-up window (line 13).
- We get the frame as the output.
Code: When the user provides the Input
import cv2 #taking time in seconds time_stamp = int(input("Input the time in second where you want the snapshot?")) #converting to miliseconds time = time_stamp * 1000 #providing path of the video video_capture = cv2.VideoCapture('d:/video.mp4') #capturing the frame in provided time. video_capture.set(cv2.CAP_PROP_POS_MSEC, time) success, image = video_capture.read() if success: # save frame as JPEG file cv2.imwrite("frame.jpg", image) cv2.imshow("image_at_" + str(time_stamp)+" second.jpeg", image) cv2.waitKey()
Explanation when the user provides the Input:
- Importing the OpenCV library on the code (Line 1).
- A variable named
time_stampwill take the input from the user. Users will enter the time in seconds they want the frame for (Line 4).
- In line 7, we have converted seconds to milliseconds.
- The video_capture variable ensures that we are taking the file path using the VideoCapture function (Line 10).
video_capture.set(cv2.CAP_PROP_POS_MSEC, time) lets us capture the frame (Line 13). This takes time in milliseconds.
.read()reads the frame, and success takes the boolean value (Line 14).
.imwritesaves the file name.
.imshowdisplays the name with which the frame will be saved (Line 18).
- We get the frame as we see it in the output.
With this, we have completed our tutorial. Learn, how to draw a circle on an image using OpenCV Python