The Ubuntu environment uses python to significantly replace different backgrounds for videos with transparent channels

The Ubuntu environment uses python to significantly replace different backgrounds for videos with transparent channels

Preface: Although pr video processing software can also replace different backgrounds one by one for videos with transparent channels, if you want to manually replace one hundred and one thousand of these videos, it is obviously a runaway operation.This article documents how python can be used in the Ubuntu environment to replace videos with transparent channels in a large number of different backgrounds, mainly recording the configuration of the environment and the usage of the project.

1. Environmental Configuration

1.1 Download Code

The script code has been submitted to GitHub at

* The script code is also pasted below

import time
import shutil

import cv2
import os
from moviepy.editor import VideoFileClip, CompositeVideoClip


def extract(videopath, index=EXTRACT_FREQUENCY):
    video = cv2.VideoCapture()
    if not
        print("can not open the video")
    count = 1
    while True:
        _, frame =
        if frame is None:
        if count % EXTRACT_FREQUENCY == 0:
            index += 1
        count += 1
    print("Totally save {:d} pics".format(index - 1))
    a = index - 1
    return a

def copy_photo(photo_path, n):
    img = cv2.imread(photo_path, cv2.IMREAD_COLOR)
    path_photo = photo_path.split('.', 1)[0]

    except OSError:
    for i in range(n):
        name = path_photo + '/' + (str(i)).zfill(4) + '.png'
        cv2.imwrite(name, img)
    return path_photo

def become_video(fg_in_bg, name1):
    cap = cv2.VideoCapture(name1)
    fgs = int(cap.get(cv2.CAP_PROP_FPS))
    pictrue_in_filelist = os.listdir(fg_in_bg)
    pictrue_in_filelist.sort(key=lambda x: int(x[:-4]))
    name = fg_in_bg + "/" + pictrue_in_filelist[0]
    img = cv2.imread(name)
    h, w, c = img.shape
    size = (w, h)

    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out_video = name1.split('.', 1)[0] + 'out.avi'
    video_writer = cv2.VideoWriter(out_video, fourcc, fgs, size)

    for i in range(len(pictrue_in_filelist)):
        pictrue_in_filename = fg_in_bg + "/" + pictrue_in_filelist[i]
        img12 = cv2.imread(pictrue_in_filename)
    return out_video

def add_zm(fg_in_bg_avi, zm_video_path, i):
    clip1 = VideoFileClip(fg_in_bg_avi)
    clip3 = VideoFileClip(zm_video_path, has_mask=True)
    video = CompositeVideoClip([clip1, clip3])
    except OSError:

    out_name = "out/" + zm_video_path.split('.', 1)[0] + "out"

    name = out_name + i + ".mp4"
    video.write_videofile(name, audio=True)  # No audio first
    return name

if __name__ == '__main__':

    start = time.clock()

    mova = ''
    pictrue_path = "input"
    n = extract(mova)

    bg_list = os.listdir(pictrue_path)

    bg_list.sort(key=lambda x: int(x[2:-4]))

    for _ in bg_list:
        for_mat = _.split('.', 1)[-1]
        for_name = _.split('.', 1)[0]

        print("Start processing" + for_name)

        name1 = pictrue_path + '/' + _
        if for_mat == 'png' or for_mat == 'jpg':
            path_photo = copy_photo(name1, n)

            video = become_video(path_photo, mova)

            name = add_zm(mova.split('.', 1)[0] + 'out.avi', mova, for_name)

            os.remove(mova.split('.', 1)[0] + 'out.avi')  # Intermediate Products
            print("complete" + name)
            # If there is a video in the background

    end = time.clock()

    print('Running time: %s Seconds' % (end - start))

1.2 Create a virtual environment and install the toolkit

In order not to affect the use of toolkits between different projects, you need to create a virtual environment.In Ubuntu, I recommend using anaconda's conda command to create it.The terminal command is:

conda create -n envname python=3.6  # Create a virtual environment named envname for Python version 3.6

Step 2 enters the virtual environment and installs the runtime toolkit required for the project

conda activate envname  # Enter virtual environment
pip install -r requirement.txt -i #Use pip to download the installation kit from the Tsinghua mirror source

2. How to use the project

2.1 Data preparation

First, place the video with transparent channel in the same directory as the script file to ensure that the transparent channel video is in mov format; second, place the background picture in the input folder of the same directory as the file, and make sure that the size, width and height of the picture are the same as the video.

Example pictures and videos can be downloaded on the network disk: Link:

Extraction Code: srpy

2.2 Running Programs

The terminal command is as follows:


3. Result Display

Forty-five original articles were published, 24 were praised, 3395 were visited
Private letter follow

Tags: Python Ubuntu github Lambda

Posted on Thu, 12 Mar 2020 01:07:51 -0400 by y.t.