Extract Video Frames from Webcam and Save to Images using Python
OpenCV library can be used to perform multiple operations on videos. Let’s try to do something interesting using CV2. Le’s record a video as form webcam and break the video into the frame by frame and save those frames.
Installation
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install opencv-python
Steps Required.
- Open the Video file using cv2.VideoCapture(<path_of_video>) or If you do not have any video you can directly use your inbuilt camera using cv2.VideoCapture(0) command.
- Read frame by frame
- Save each frame using cv2.imwrite()
- Release the VideoCapture and destroy all windows
Below is the implementation.
Python3
import cv2 # Opens the inbuilt camera of laptop to capture video. cap = cv2.VideoCapture( 0 ) i = 0 while (cap.isOpened()): ret, frame = cap.read() # This condition prevents from infinite looping # incase video ends. if ret = = False : break # Save Frame by Frame into disk using imwrite method cv2.imwrite( 'Frame' + str (i) + '.jpg' , frame) i + = 1 cap.release() cv2.destroyAllWindows() |
Output: