Saving live video frames – Python OpenCV
In this tutorial, we will see how we save frames of a live video using OpenCV in Python. A video is simply images or frames moving one after another at a specified frequency. We get a single frame by stopping the video or images in sequence. Now let’s see about OpenCV a library in Python aimed at real-time computer vision.
About OpenCV:
OpenCV is a substantial, interactive toolbox supporting image acquisition and machine learning including face recognition. Today, it contributes significantly to include the practice of artificial intelligence, which itself is essential in contemporary systems. We can install OpenCV by running pip install opencv-python
it on our terminal window.
Code for saving live video frames using OpenCV :
#Importing libaries import cv2 from datetime import datetime import os #reads or opends the webcam # we have passed the argumnet 0 to specify we are using the default webcam webCam = cv2.VideoCapture(0) #folder where we want to store the frames #if not given saves in the same dir as the file. path = r'D:\frames' # changing directory to given path os.chdir(path) current_frame = 0 #tells us on what frame we are present wait = 0 while True: #captures image by images information success, frame = webCam.read() font = cv2.FONT_HERSHEY_PLAIN cv2.putText(frame, str(datetime.now()), (20, 40), font, 2, (255, 255, 255), 2, cv2.LINE_AA) cv2.imshow("output", frame) # wait for user to press any key key = cv2.waitKey(100) # wait variable is to calculate waiting time wait = wait+100 if key == ord('q'): break if wait == 5000: filename = 'Frame_'+str(current_frame)+'.jpg' # Save the images in given path cv2.imwrite(filename, frame) current_frame +=1 wait = 0 # close the camera webCam.release() # close open windows cv2.destroyAllWindows()
Explanation of the above code:
- First and foremost, we have imported all the libraries, which are DateTime, OS, and OpenCV. DateTime is used to show the live time and date of the video, and it is shown in the frames as well.
- Next, we have a variable called webCam, which will open the webcam of the computer. 0 in the argument indicates that we are using the default webcam.
- The path is chosen to store the frames we are capturing from the video.
- A variable called current_frames specifies that we are in the recent frame. The wait variable is set to 0.
- cv2.putText assists in displaying the text of the date and time in the frames we are capturing.
- cv2.imshow displays the camera from which we are capturing the frames.
- To stop the whole process of capturing the frames, we can press “q.” The whole code terminates.
- This is how we save frames using OpenCV in python.
With this, we have concluded our tutorial. Learn, to find a specific object in an image using OpenCV in Python
Leave a Reply