Fundamentals 9 min read

How to Convert a Dancing Video into an ASCII Art Video Using Python

This tutorial walks through downloading a Bilibili dance video, extracting GIF frames, converting each frame to ASCII art, renaming and ordering the frames, converting them to images, and finally assembling them into a video with background music using Python libraries such as you-get, OpenCV, Pillow, and moviepy.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Convert a Dancing Video into an ASCII Art Video Using Python

This guide shows how to turn a dancing video into a "code dance" by processing the video with Python. The workflow includes downloading the video, extracting GIF frames, converting frames to ASCII art, renaming and ordering the frames, converting them to images, and finally assembling them into a video with background music.

Core Function Design

The process is divided into six main steps:

Download the video from Bilibili.

Extract GIF segments and convert each frame to ASCII characters.

Rename GIF files to reflect frame order.

Convert the ordered GIF frames to JPG images.

Combine the images into a video.

Add background music to the final video.

Implementation Steps

1. Download Video

Install you-get to fetch the video:

pip install you-get

Then download the video with:

you-get -o <local_path> <video_url>

2. Extract GIF and Convert to ASCII

Use a GIF cutter (e.g., the built‑in tool of the Xunlei player) to extract 20‑second clips, name them sequentially, and then convert each GIF to ASCII using ASCII Animator . Adjust the character density by setting the pixel‑width parameter and output an animated ASCII GIF.

3. Rename GIF Files

Import the required libraries and run a renaming script to order the GIFs correctly.

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

def rename_gif():
    file_list = os.listdir("./temp")
    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)  # 重命名,覆盖原先的名字

4. Convert GIF to JPG Images

Transform the ordered GIF frames into JPG files:

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)
        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)

5. Assemble Images into Video

Install OpenCV and use the following function to create a video from the JPG sequence:

pip install opencv-python
def charts2video(img_path, video_path):
    """Convert images in a directory to a video.
    Args:
        img_path: Path to the image folder.
        video_path: Output video file path.
    """
    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()

6. Add Background Music

Use moviepy to extract the original audio and merge it with the ASCII video:

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')

After completing these steps, the original dancing video is transformed into an ASCII‑art video synchronized with the original background music.

Pythonvideo processingopencvascii artyou-getMoviePy
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.