Self timer 66 Python ffmpeg bulk compression video

Case story: Bug videos are found during the test, which need to be provided for reference in the development of Bug solution,
However, after video shooting, it is too large to be transmitted on wechat client,
Therefore, there have been testers using winzip to compress in batches (part1, part2, part3),
Then transmit the "chaos" of video compression package through wechat:

As the test director, I feel ashamed that the people below me are "compressing video",
(1) . video files are binary files, but winzip can't compress anything,
winzip compression software is generally only suitable for compressing text data files.
(2) Video compression should use video coding technology to achieve secondary coding compression, the most commonly used in the industry is definitely ffmpeg.exe Tools.


For example, when a Bug video is too large to be uploaded to the Bug system as an attachment,
Being able to do video compression is one of the essential abilities of qualified testers,
This paper mainly introduces how to achieve the bulk compression of video through ffmpeg.


Basic knowledge of video
  1. Video file is composed of video stream and audio stream. It is a dynamic image produced by playing a series of pictures quickly. The aggregate of audio and the audio stream of video file are generally very small, but the video stream is very large. The size of video stream mainly depends on three factors: encoding technology, resolution and frame rate.

  2. Codec is a coding technology for compressing multiple pictures, such as a video composed of multiple pictures,
    If the pixels of the connected pictures are similar, only the difference pixels can be recorded,
    Thus, the video file is minimized without affecting the image quality,
    The default encoding format of ffmpeg is: H.264 In fact, there are many coding formats,
    For example, Mpeg4, WMV10, H.263 wait.

  3. Resolution resolution is the image size of each frame (each picture) of video, which is composed of one pixel.

  4. The frame rate is fps, the number of pictures per second, generally more than 4 pictures per second (> 4 fps) can have obvious video animation effect.

  5. Video Container is a Container format used to encapsulate video and audio streams. Generally, it has. MP4,. 3gp,. Avi,. MOV, etc.

  6. bitrate is the amount of data per second. The amount of data is basically affected by video coding format, resolution and frame rate.

  7. Every time the video is compressed, the amount of data in the video will be reduced and irreversible!

Preparation stage
  1. The download address of ffmpeg can go to: ffmpeg audio video image codec tool Check out this article.
    Common command templates for video compression are:
    ffmpeg -i input.mp4 -s 640x480 -r 12 -y output.mp4
    The above command template can input.mp4 Recoding (at frame rate of 12fps and resolution of 640x480),
    And save as output.mp4 - y means that if you already have this file, you can overwrite it without asking.

  2. If we want to compress the video in batches, we still use the I / O mode. The file structure is as follows:

	+---Input_Video: batch the video to be compressed
	|       1.mp4
	|       2.mp4
	|       
	+---Output_Video - batch output compressed video with a suffix_ c. Representation and conversion complete.
	|       1_c.mp4
	|       2_c.mp4
	|
	\convert_video.py  #Python video transcoding script, double-click to run
  1. Remember to ffmpeg.exe Drop it to the Path of system Path environment variable.

Python batch script form

Remember the essence of batch scripts: execute statements in batch order

# coding=utf-8

import os

NEW_RESOLUTION = "640x480"  # Target resolution, constant
NEW_FPS = 12  # Target frame rate, constant

curpath = os.getcwd()  # Get current path
input_dir = os.path.join(curpath, "Input_Video")
output_dir = os.path.join(curpath, "Output_Video")
input_video_list = os.listdir(input_dir)  # Get video list

# If there is no Output_Video, create this folder
if not os.path.exists(output_dir):
    os.mkdir(output_dir)

# Start to batch encode and compress video transcoding
for each_video in input_video_list:
    video_name, _ = os.path.splitext(each_video)  # A kind of It's meaningless. It's just a useless code. It's just a hole
    ffmpeg_command = ("ffmpeg -i %s%s%s -s %s -r %s -y %s%s%s_c.mp4" % (
        input_dir, os.sep, each_video, NEW_RESOLUTION, NEW_FPS, output_dir, os.sep, video_name))
    print(ffmpeg_command)
    os.system(ffmpeg_command)

os.system("pause")

Python procedure oriented function form

Process function oriented programming thinking should be as follows:
How many functions do you need to do this.
It is better to encapsulate all functions as much as possible, only exposing some parameter interfaces.

# coding=utf-8

import os


def convert_video(input_video_path, new_resolution, new_fps, output_video_path):
    ffmpeg_command = ("ffmpeg -i %s -s %s -r %s -y %s" % (
        input_video_path, new_resolution, new_fps, output_video_path))
    print(ffmpeg_command)
    os.system(ffmpeg_command)


curpath = os.getcwd()  # Get current path
input_dir = os.path.join(curpath, "Input_Video")
output_dir = os.path.join(curpath, "Output_Video")
input_video_list = os.listdir(input_dir)  # Get video list

# If there is no Output_Video, create this folder
if not os.path.exists(output_dir):
    os.mkdir(output_dir)

# Start to batch encode and compress video transcoding
for each_video in input_video_list:
    video_name, _ = os.path.splitext(each_video)  # A kind of It's meaningless. It's just a useless code. It's just a hole
    input_video_path = input_dir + os.sep + each_video
    output_video_path = output_dir + os.sep + video_name + "_c.mp4"
    convert_video(input_video_path, "640x480", "12", output_video_path)
os.system("pause")

Python object oriented class form

The programming thinking of object-oriented class should be as follows:
If you are given a blank world, what kinds of things do you need in this world,
What are the common attributes and methods of these kinds of things,
What is the relationship between these kinds of things (objects) and other kinds of things (objects).
Try to encapsulate these classes and only expose the external attributes (variables) and methods (functions).

# coding=utf-8

import os


class VideoConverter(object):
    def __init__(self, input_video_path, new_resolution, new_fps, output_video_path):
        self.input_video_path = input_video_path
        self.new_resolution = new_resolution
        self.new_fps = new_fps
        self.output_video_path = output_video_path

    def convert_video(self):
        ffmpeg_command = ("ffmpeg -i %s -s %s -r %s -y %s" % (
            self.input_video_path, self.new_resolution, self.new_fps, self.output_video_path))
        print(ffmpeg_command)
        os.system(ffmpeg_command)


if __name__ == '__main__':
    curpath = os.getcwd()  # Get current path
    input_dir = os.path.join(curpath, "Input_Video")
    output_dir = os.path.join(curpath, "Output_Video")
    input_video_list = os.listdir(input_dir)  # Get video list

    # If there is no Output_Video, create this folder
    if not os.path.exists(output_dir):
        os.mkdir(output_dir)

    # Start to batch encode and compress video transcoding
    for each_video in input_video_list:
        video_name, _ = os.path.splitext(each_video)  # A kind of It's meaningless. It's just a useless code. It's just a hole
        input_video_path = input_dir + os.sep + each_video
        output_video_path = output_dir + os.sep + video_name + "_c.mp4"
        v_obj = VideoConverter(input_video_path, "640x480", "12", output_video_path)
        v_obj.convert_video()
    os.system("pause")

Download the case materials

Including: Input_Video (including one H.264_1280x720_24fps.mp4 Video), Python script
Go to the official website to download
Wusanren products, please feel free to download!

The above three forms of tips are just for training and training of programming thinking. In fact, the main core code is ffmpeg command,
If batch processing is not involved, the transcoding can be realized by directly typing the original ffmpeg command,
The above can basically compress 100M video to about 10M.


For more and better original articles, please visit the official website: www.zipython.com
Selfie course (Python course of automatic test, compiled by Wu Sanren)
Original link: https://www.zipython.com/#/detail?id=52f5f5ed29a14614bc522754af3b7b4e
You can also follow the wechat subscription number of "wusanren" and accept the article push at any time.

Keywords: Python Programming encoding codec

Added by ciaranmg on Tue, 19 May 2020 20:11:39 +0300