Welcome folks today in this blog post we will be extracting frames of mp4 video
and saving it as png and jpg
images inside command line using the opencv
library. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library
using the below pip command as shown below
pip install opencv-python
After that you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import cv2 import os cam = cv2.VideoCapture("video.mp4") try: if not os.path.exists("data"): os.makedirs("data") except OSError: print("Error: Creating directory of data") currentframe = 0 while(True): ret,frame = cam.read() if ret: name = './data/frame' + str(currentframe) + '.jpg' print("Creating..." + name) cv2.imwrite(name,frame) currentframe +=1 else: break cam.release() |
As you can see we are importing the opencv
library and then we are importing the video.mp4
file and then we are using the while
loop to extract the frames from the video file and saving it inside the root
directory as image
file using the imwrite()
method. And then we are incrementing the currentframe
of the video.
Now as you execute the above
python script it will create the data
directory and inside it we will have the images
which will be created from the video.mp4
file