Mastering Artificial Intelligence

Extracting and Saving Video Frames using OpenCV-Python

In this tutorial, I will show you how to extract and save frames from a video file. Prerequisites are Chapter 1 and 2.

Steps:

Open the Video file or camera using cv2.VideoCapture()

Read frame by frame

Save each frame using cv2.imwrite()

Release the VideoCapture and destroy all windows

Now, Let’s code

Extracting and Saving Video Frames using OpenCV-Python

Python

1

2

3

4

5

6

7

8

9

10

11

12

importcv2

# Opens the Video file

cap=cv2.VideoCapture('C:/New/Videos/Play.mp4')

i=0

while(cap.isOpened()):

ret,frame=cap.read()

cv2.imwrite('kang'+str(i)+'.jpg',frame)

i+=1

cap.release()

cv2.destroyAllWindows()

If you don’t have any video, no need to worry. Open the camera instead of the file using cv2.VideoCapture(0) and start extracting frames.

Use: We can perform a number of operations on these frames like crop, flip, reverse etc. save them into a list and iterate over them to get cropped/flipped/reversed video. (See How you can make Video from images)

Hope you enjoy reading. If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time