Thursday, December 26, 2024
Google search engine
HomeLanguagesExtract Video Frames from Webcam and Save to Images using Python

Extract Video Frames from Webcam and Save to Images using Python

There are two libraries you can use: OpenCV and ImageIO. Which one to choose is situation-dependent and it is usually best to use the one you are already more familiar with. If you are new to both then ImageIO is easier to learn, so it could be a good starting point. Whichever one you choose, you can find examples for both below:

ImageIO

Installation:

pip install imageio[ffmpeg]

Usage:

Reading frames from a webcam and saving them as images:

Python3




import imageio.v3 as iio
  
for frame_count, frame in enumerate(iio.imiter("<video0>")):
    iio.imwrite(f"frame_{frame_count}.jpg", frame)
    if frame_count > 10:
        break


Reading frames from a video and saving them as images:

Python3




import imageio.v3 as iio
  
for frame_count, frame in enumerate(iio.imiter("path/to/video.mp4")):
    iio.imwrite(f"frame_{frame_count}.jpg", frame)


OpenCV

Installation:

pip install opencv-python

Usage:

Reading frames from a webcam and saving them as images:

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: 

python opencv extract frames from video

Reading frames from a video and saving them as images:

Python3




import cv2
  
# Opens the inbuilt camera of laptop to capture video.
cap = cv2.VideoCapture("path/to/video.mp4")
  
success, image = cap.read()
frame_count = 0
while success:
    cv2.imwrite(f"extracted_images/frame_{frame_count}.jpg", image)
    success, image = cap.read()
    frame_count += 1
  
cap.release()


RELATED ARTICLES

Most Popular

Recent Comments