Have you ever seen a fairy dance? Let's use python to make a little fairy code dance video together

foreword

Recently, I saw a beautiful fairy dancing video on station B. I watched it hundreds of millions of times in a loop, and I can't leave for a long time!

Looking at Miss Xianzi's disco video, what else can I do except one-click three times? On a whim, can I turn the little fairy's disco video into a code dance?

Just do what you say, and today I will teach you how to turn the dancing video into a code dance and dance with the fairy sister~

Video source: [Zi Yan] Have you ever seen a fairy dance [Qianzhan]

Skip directly to the end of the article to get exclusive fan benefits.

1. Core function design

In general, we need to divide it into the following steps:

  1. Download Miss Sister's video from station B
  2. Capture GIF from video and convert the captured GIF to ASCII characters
  3. Rename and sort the converted character gif according to the order of each frame
  4. Convert sorted frame gif to picture
  5. Merge character pictures into video
  6. video add background music

2. Implementation steps

1. Download the video

First we need to prepare, install you-get to download videos.

pip install you-get

insert image description here
After the installation is complete, download the video locally via you-get.

Fairy sister dance video link: https://www.bilibili.com/video/BV124411Q7iV

you-get -o 本地保存路径 视频链接 

insert image description here

In this way, we successfully downloaded the video to the local.
insert image description here

2. Intercept GIF and convert to ASCII characters

Next, we need to intercept the GIF of the downloaded video. There are many methods, which can also be implemented with python.

Because the GIF needs to be converted into ASCII characters later, the length of the intercepted GIF should not be too long, so here is the introduction of the gif interception tool that comes with the Thunder player, and each interception is 20s.
insert image description here
After cutting out each section, you can name the gif in the order 1 2 3.

insert image description here
insert image description here

Use ASCII Animator to convert each frame of the captured GIF to ASCII . We can modify the character density of the conversion by setting the number of characters per 100 pixel width. The output type can choose animation ASCII (.gif).
insert image description here
We can find the temp file under the directory file, which is the ASCII gif of each frame converted in each gif stored. Next, we need to process these ASCII gifs, and we can copy the folder to the python project.

insert image description here

3. GIF Rename

The old rule, at first we imported all the libraries that we will use later.

import os
import re
import shutil
import cv2
from PIL import Image
import moviepy.editor as mpy

All the converted ASCII gifs have been obtained. In order to merge the pictures into a video later, we will sort these gifs.

We first read from the temp folder, filter out all the suffixes with .gif , and then rename these gifs according to the naming rules to facilitate later sorting.

def rename_gif():
    file_list = os.listdir("./temp")  # 读取当前文件夹所有文件
    # print(file_list)
    print("检测到文件夹下图片:")
    n = len(file_list)
    num_list = []
    num1 = num2 = 0
    for i in range(n):
        s = str(file_list[i])
        if s[-4:] == ".gif":  # 检查后缀
            res = re.findall(r"\d+", s)
            if res[0] == '1':
                num1 += 1
            if res[0] == '2':
                num2 += 1
            src = os.path.join(os.path.abspath('./temp/'), s)  # 原先的图片名字
            dst = os.path.join(os.path.abspath('./temp/'), res[0] + '-' + res[1]+'.gif')  # 根据自己的需要重新命名
            os.rename(src, dst)  # 重命名,覆盖原先的名字
    num_list.append(num1)
    num_list.append(num2)
    file_list = os.listdir("./temp")  # 读取当前文件夹所有文件
    for i in range(n):
        s = str(file_list[i])
        if s[-4:] == ".gif":  # 检查后缀
            res = re.findall(r"\d+", s)
            src = os.path.join(os.path.abspath('./temp/'), s)  # 原先的图片名字
            a = int(res[0])-1
            index = a*num_list[a-1]
            dst = os.path.join(os.path.abspath('./temp/'), str(index + int(res[1])) + '.gif')  # 根据自己的需要重新命名
            os.rename(src, dst)  # 重命名,覆盖原先的名字

After the gif is renamed, all the gifs have been arranged in the order of each frame. When we synthesize the video later, we only need to merge and add according to the name of the picture.
insert image description here

4. Convert gif to jpg

Next, we want to convert the gifs arranged in frame order into jpg images .

def gif2img(gif_path):
    gifs = os.listdir(gif_path)
    gifs.sort(key=lambda x: int(x[:-4]))  # 以名称字符串的数字从小到大排序
    for gif in gifs:
        im = Image.open(gif_path+gif)  # 打开gif格式的图片
        im = im.convert('RGB')
        if not os.path.exists('./img'):
            os.makedirs('./img')
        for i, frame in enumerate(iter_frames(im)):
            frame.save('./img/' + gif[0:-4] + '.jpg', **frame.info)  # 保存成jpg格式

insert image description here

5. Synthesize code dance video

Picture synthesis video, here we use the python-openvc module to achieve, also if you have not installed a friend before, you need to install it first.

pip install opencv-python

We can pass the path of the picture folder into the parameters, and we can also set how many pictures per second by fps .

def charts2video(img_path, video_path):
    """将给定目录下的图片转成视频
    Args:
        img_path: 图片路径
        video_path: 输出视频的路径和名称

    Returns: 图片转成的视频
    """
    images = os.listdir(img_path)
    images.sort(key=lambda x: int(x[:-4]))  # 以名称字符串的数字从小到大排序  
    fps = 12  # 帧数
    fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
    im = Image.open(img_path + images[0])
    video_writer = cv2.VideoWriter(video_path, fourcc, fps, im.size)
    for img_i in images:
        frame = cv2.imread(img_path + img_i)
        print('开始将 ' + img_i + ' 加入视频\n')
        video_writer.write(frame)  # 注意:图片尺寸必须和视频尺寸一样,不然不会被加入视频中!!!
    video_writer.release()

insert image description here

6. Add background music

The code dance is done, the last step is to add the background music from the video to the code dance. We use the moviepy module to capture the background music of the original video and save it, and finally insert the audio into the code dance video and save it.

def add_music():
    # 读取代码视频
    my_clip = mpy.VideoFileClip('asc.mp4')
    # 截取背景音乐
    audio_background = mpy.AudioFileClip('dance.mp4').subclip(0, 60)
    audio_background.write_audiofile('bk.mp3')
    # 视频中插入音频
    final_clip = my_clip.set_audio(audio_background)
    # 保存最终视频
    final_clip.write_videofile('char_video.mp4')

So far, the little fairy dancing video is converted into code dance and it is complete~

I have uploaded the last code dance video to station B, everyone can enjoy it together.

【Ziyan】Have you ever seen a fairy dance?

Dragon Junior | Text

The source code and data have been uploaded, pay attention to the public account at the end of the article and reply to [source code] to get the complete source code

Python's past highlights:

Guess you like

Origin blog.csdn.net/hhladminhhl/article/details/118463344