Coders Packet

Video Compression using OpenCV in Python

By Aryan Yadav

Any video can be compressed using the command line arguments with users flexibility in choosing the video and the amount by which video should be compressed using Python.

Pre-requisite:

Python OpenCV module should be installed in your system.

Methodology: 

1. Import the following modules: cv2, os, and sys

2. Raise exceptions for the following error:

a. Arguments specified by user should be 3 only, if not then raise error.

b. To check the format of the file if it is a video file or not using split() function.

c. Size entered by the user should be in range(1,99), if not then raise error.

d. To if the file exists in dictonary or not using os library.

3. Read the video file using the cv2.VideoCapture() method.

4. Save the compressed video using cv2.VideoWriter method.

5. Run a loop till the video is open.

6. Inside the loop extract all the frames of the video using read() method.

7. Pass these frame along with the compression size to a user-defined function which returns the resized frame as per the users compression input using resize() method.

8. Store the resized frames and write it into the saved video variable using write() method.

How to run in your system using the command line?

1. Change the directory to where your Python file, video and the OpenCV env is setup.

2. Then type the following commands,

python filename.py videoname.mp4 50

3. Finally your compressed video will be ready in the same folder.

Download Complete Code

Comments

  • Yasar :

    Your code is working fine but the compressed file doesn't have audio it's missing.

    Kindly help to solve this issue

  • Reply to this comment