convert video to images in python

To convert a video to images in python, we can use the OpenCV library. The following code will read a video file and save its frames as separate images:

main.py
import cv2

# Open the video file
video = cv2.VideoCapture('video.mp4')

# Initialize a counter for the frames
counter = 0

# Loop through the frames of the video
while True:
    # Read a frame
    ret, frame = video.read()

    # If the frame was not successfully read, break out of the loop
    if not ret:
        break

    # Save the frame as an image
    cv2.imwrite(f'frame{counter}.jpg', frame)

    # Increment the counter
    counter += 1

# Release the video file
video.release()
491 chars
26 lines

In this code, we first open the video file using cv2.VideoCapture. We then loop through the frames of the video and read each frame using video.read(). We check if the frame was successfully read using the ret variable. If it was, we save the frame as an image using cv2.imwrite. Finally, we release the video file using video.release().

gistlibby LogSnag