Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 OpenCV Script to Extract Frames of MP4 Video & Save it as PNG/JPEG Images

Posted on January 23, 2023

 

 

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

 

 

Python
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

 

 

 

Recent Posts

  • Android Java Project to Capture Image From Camera & Save it in SharedPreferences & Display it in Grid Gallery
  • Android Java Project to Store,Read & Delete Data Using SharedPreferences Example
  • Android Java Project to Download Multiple Images From URL With Progressbar & Save it inside Gallery
  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme