FFMPG + Python achieve large separate video watermark + + based on the combined credit

Operating System: Mac 10.15.2

Author: DisenQF

QQ: 610039018

A, FFMPG installation environment

1.1 update brew source

Since the time brew command to install the software, has looks brew.git, homebrew-core.git, homebrew-bottles and other software source, then we can replace this source into Alibaba warehouse, then when you install the software, it will accelerate.

1.1.1 update brew.git

cd "$(brew --repo)" 
git remote set-url origin https://mirrors.aliyun.com/homebrew/brew.git 

If the source before the restore, execute the following command:

git remote set-url origin https://github.com/Homebrew/brew.git

1.1.2 update homebrew-core.git

cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core" 
git remote set-url origin https://mirrors.aliyun.com/homebrew/homebrew-core.git 

Address of the original warehouse is: https://github.com/Homebrew/homebrew-core.git

1.1.3 update homebrew-bottles

echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.aliyun.com/homebrew/homebrew-bottles' >> ~/.bash_profile 
source ~/.bash_profile 

If the previous reduction, through the vi editor, open the file .bash_profile, will HOMEBREW_BOTTLE_DOMAINbe deleted.

1.2 install ffmpeg

There are two related github in warehouses, i.e. homebrew-ffmpeg and varenc / homebrew-ffmpeg , the use of a warehouse, the following specific installation:

brew tap homebrew-ffmpeg/ffmpeg
brew install homebrew-ffmpeg/ffmpeg/ffmpeg
brew options homebrew-ffmpeg/ffmpeg/ffmpeg

Tip] HomeBrew temporary download files directory ~ / Library / Caches / Homebrew / downloads, if particularly slow during download and install a file, you can do Ctrl + C to exit the installation and use professional download tools (Thunder), when downloading When finished, you can find the relevant file and change the name to download the file name. As donwloads file directory under the file:

0b4dcf92e1664a17fefc4c0f7993a9943849d88144a7a22c4b5458271c1527ea--pip-19.3.1.tar.gz
0cd4162bd88b80d7d824536c0dfb4d9b6432556a96c75308368491218b766b44--ffmpeg-4.2.2.tar.xz
4f03f7d12fc06e90f55a39f67ee01efd978fe4d084982c0c906baf012e214451--Python-3.7.5.tar.xz

If the installation is successful, you can view ffmpeg command help, command is as follows:

ffmpeg -h

Second, install the Python environment

2.1 Installation Python3

brew install python3

After a successful installation, you can do `python -v` command to test the Python version.

The default installation path is/Library/Frameworks/Python.framework/Versions/3.7

Then confirm pip3 is installed, it is dependent on Python's package management tool command, the command is `pip3 -V`

2.2 Installation ffmpeg-python

pip3 install ffmpeg-python

Ffmpeg need to get through the video module in Python scripts media information, such as the duration and the like.

 

Third, the preparation of related resources

3.1 credit video

In general, the credit-video formats are mp4 (H264 / H263), you need to mp4 mpg file into a unified format, the command as follows:

ffmpeg -i start.mp4 -qscale:v 1 start.mpg

3.2 watermark font

If you add text watermark to the video after the merger, you need to select the appropriate font file and font files and the python script in the same directory, the following list:

run_sep.py
end.mpg
start.mpg
f1.ttf

As shown above, f1.ttf compared to the font file resources. This is a font of clouds hollow body.

If the watermark using similar logo.png picture, this image will also be placed under the above directory.

3.3 target video resources

When the need to convert the mp4 file in the same directory, run python script, specify the directory and the size of video can be separated. The separation rule for 15-20 minutes, less than 30 minutes if the video is not separated.

[Note] Make sure the file name without a space, because the script Python program, you need to execute ffmpeg command under mac.

 

Four, ffmpeg related commands

4.1 delimited video

ffmpg -i xxxx.mp4 -ss 00:15:00  -t 00:15:00 -vcodec copy -acodec copy xxx-out.mp4

Related parameters:

  • -i represents the input of the input video source

  • -ss represents the start time, i.e., such as 00:15:00 0:15:00 Start

  • -t represents the end of the length, such as 00:15:00, i.e., from the start -ss, separated out 15 minutes

  • -vcodec / -acodec denotes a video and audio transcoding transcoding mode, using the copy represents a copy, indicates that no compression process.

  • xxx-out.mp4 denotes a video storage location after the separator.

4.2 composite video

4.2.1 create a composite profile

Such as the file name merge.txt, reads as follows:

file start.mpg
file  Scrapy/7375ef1c9b7f559e17de206ded7aed27.mpg
file end.mpg
【注意】文件中不能带有中文名称,所以存放视频资源的文件目录必须修改为英文。

4.2.2 composite video command

ffmpeg -f concat -i merge.txt -c copy xxxx-merge.mpg -y

As shown in the command xxxx-merge.mpgthat is synthesized video resource name.

4.3 Text Watermark

ffmpeg -i xxx.mp4 -vf "drawtext=fontfile=f1.ttf: text=\'千锋人工智能学院\':x=(w-text_w)-50:y=100:fontsize=50:fontcolor=blue:shadowy=2" -b:v 3000k -s 1280*720 xxx-water.mp4

In order to do this, if the newspaper font-related errors (drawtext), you need to install freetype. Installation command as follows:

brew install freetype
brew reinstall ffmpeg --with-freetype

You can check whether the installed dependencies by command, the command is as follows:

brew info ffmpeg

4.4 LOGO watermark

4.4.1 lower right corner position

ffmpeg -i xxx.mp4 -i logo.png -filter_complex 'overlay=main_w-overlay_w-10:main_h-overlay_h-10' -s 1280*720 output-water.mp4

Parameter Description:

  • -filter_complex: Stacks

    • main_w: Video width

    • main_h: Video height

    • overlay_w: picture watermark Width

    • overlay_w: picture watermark Width

  • size screen size -s 1280 * 720 target video format that is 720P. Of course, the resolution of the original video is higher than it is.

4.4.2 lower left corner position

X and y parameters can be specified, the following command:

ffmpeg -i xxx.mp4 -i logo.png -filter_complex 'overlay=x=10:y=main_h-overlay_h-10'  -s 1280*720 output-water.mpg

4.5 video format conversion

Mp4 mpg mainly exchange conversion and, when converted, primarily by -qscale: The value v, 1 is converted into mpg i.e., to then go to 2 mp4.

4.5.1 mp4 turn mpg

ffmpeg -i xxx.mp4 -qscale:v 1 xxxx.mpg

4.5.2 mpg transfer mp4

ffmpeg -y -i xxxx-merge.mpg -qscale:v 2 xxx.mp4

Five, Python coding

Create run_sep.py file, make additions as follows.

5.1 guide package

from sys import argv
import os
import re
import subprocess

import ffmpeg
from hashlib import md5

5.2 Run function package

def shell_cmd(cmd):
    ternimal = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    for info in ternimal.communicate():
        try:
            print(info.decode())
        except:
            break

5.3 Single file processing

def process_file(file_path, out_file_path=None):
    # file_path 为完整的文件路径
    dir_name , file_name= os.path.split(file_path)
    file_name_, ext = os.path.splitext(file_name)

    temp_file_path = os.path.join(dir_name, file_name_)+'-temp.mp4'

    if out_file_path is None:
        out_file_path = os.path.join(dir_name, file_name_)+'-qf.mp4'

    file_name_md5 = os.path.join(dir_name,md5(file_name.encode()).hexdigest())

    # 加水印
    water_cmd = f'ffmpeg -i {file_path} -vf "drawtext=fontfile=f1.ttf: text=\'千锋人工智能学院\':x=(w-text_w)-50:y=100:fontsize=50:fontcolor=blue:shadowy=2" -b:v 3000k -s 1280*720 {temp_file_path}'
    print(water_cmd)
    shell_cmd(water_cmd)

    # 将带水印的视频文件转成 mpg文件
    mpg_convert_cmd = f'ffmpeg -i {temp_file_path} -qscale:v 1 {file_name_md5}.mpg'
    print(mpg_convert_cmd)
    shell_cmd(mpg_convert_cmd)

    # 合并片头片尾
    with open('merge.txt', 'w') as f:
        f.write('file start.mpg\n')
        f.write(f'file  {file_name_md5}.mpg\n')
        f.write('file end.mpg')

    merge_cmd = f'ffmpeg -f concat -i merge.txt -c copy {file_name_md5}-merge.mpg -y'
    print(merge_cmd)
    shell_cmd(merge_cmd)

    # mpg转换mp4
    convert_mgp_mp4_cmd = f'ffmpeg -y -i {file_name_md5}-merge.mpg -qscale:v 2 {out_file_path}'
    print(convert_mgp_mp4_cmd)
    shell_cmd(convert_mgp_mp4_cmd)

    # 删除临时文件
    rm_cmd = f'rm -f {file_name_md5}*'
    print(rm_cmd)
    shell_cmd(rm_cmd)

5.4 Batch file processing

def process_dir():
    sep_size = int(argv[2])  # 分隔的视频的时长(分钟)

    for mp4_file_name in filter(lambda x: x.endswith('.mp4'), os.listdir(file_path)):
        mp4_file_path = os.path.join(file_path, mp4_file_name)
        info = ffmpeg.probe(mp4_file_path)
        time_ = float(info['streams'][0]['duration'])
        # 折成15分钟一个,计算折分的次数
        n = int(time_ // (sep_size * 60) + (1 if time_ % (sep_size * 60) > 0 else 0))
        for i in range(0, n):
            if i == 0:
                end_ = '00:15:00'
            elif i < n:
                start_ = str(i * sep_size // 60).rjust(2, '0') + ':' + str(i * sep_size % 60).rjust(2, '0') + ':00'

            cmd = '-t ' + end_ if i == 0 else '-ss ' + start_ + ' -t ' + end_ if i < n - 1 else '-ss ' + start_

            out_file_path, ext = os.path.splitext(os.path.join(file_path, mp4_file_name))
            out_file_path_1 = out_file_path + '-' + str(i + 1) + ext  # 分隔的文件名,输出的文件名

            temp_file_name = file_path + "/" + md5(out_file_path_1.encode()).hexdigest()
            temp_file_path = temp_file_name + ".mp4"

            full_cmd = 'ffmpeg ' + cmd + f' -i {mp4_file_path}  -vcodec copy -acodec copy  ' + out_file_path_1
            print(full_cmd)
            shell_cmd(full_cmd)

            process_file(mp4_file_path)

When the batch file operations, that is, the specified directory of all video to find out, to separate a single video processing according to separate rules.

Get video file information ffmpeg.probe(mp4_file_path)code that returns the dictionary object, used to obtain long info['streams'][0]['duration']way to get.

5.5 program entry

if __name__ == '__main__':
    file_path = argv[1]
    if os.path.isdir(file_path):
        process_dir()
    else:
        process_file(file_path)

Sixth, automatic operation

As for all mp4 files separated by 15 minutes scrapy directory, watermarking and credit, then execute the following command:

python3 run_sep.py  /Users/apple/Desktop/mp4/scrapy  15

If not, the program starts automatically executed.

Released two original articles · won praise 3 · Views 1413

Guess you like

Origin blog.csdn.net/ahhqdyh/article/details/104744906