Extract Video Frames from Webcam and Save to Images using Python

Extract Video Frames from Webcam and Save to Images using Python

To extract frames from a webcam and save them as images, you can use the opencv-python library. Here's a step-by-step guide:

Step 1: Install the required package

First, you'll need to install the OpenCV library:

pip install opencv-python 

Step 2: Extract frames from webcam and save as images

import cv2 import os def capture_frames(save_path='captured_frames', n_frames=10): # Make the save directory if it doesn't exist if not os.path.exists(save_path): os.makedirs(save_path) # Connect to the default camera cap = cv2.VideoCapture(0) if not cap.isOpened(): print("Error: Couldn't open the webcam.") return frame_count = 0 while frame_count < n_frames: ret, frame = cap.read() # Read a frame if not ret: print("Error: Couldn't read a frame.") break # Construct the filename filename = os.path.join(save_path, f'frame_{frame_count}.jpg') # Save the frame as an image cv2.imwrite(filename, frame) print(f"Saved {filename}") frame_count += 1 # Release the webcam and destroy any OpenCV windows cap.release() cv2.destroyAllWindows() if __name__ == "__main__": capture_frames() 

This script captures 10 frames from the default webcam and saves them as images in a directory named captured_frames.

You can modify the save_path and n_frames parameters of the capture_frames function to specify a different save directory or to capture a different number of frames, respectively.


More Tags

system.drawing html-email hadoop-yarn azure-storage-files mongodb-java rstudio facet upsert homebrew buffer-overflow

More Programming Guides

Other Guides

More Programming Examples