찾다
백엔드 개발파이썬 튜토리얼Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

추천 무료 학습: python 비디오 튜토리얼

먼저 효과, 비디오는 다음과 같습니다:

캐릭터 댄스:

코드 댄스

소스 코드 :

video_2_code_video .py

import argparseimport osimport cv2import subprocessfrom cv2 import VideoWriter_fourccfrom PIL import Image, ImageFont, ImageDraw# 命令行输入参数处理# aparser = argparse.ArgumentParser()# aparser.add_argument('file')# aparser.add_argument('-o','--output')# aparser.add_argument('-f','--fps',type = float, default = 24)#帧# aparser.add_argument('-s','--save',type = bool, nargs='?', default = False, const = True)# 是否保留Cache文件,默认不保存class Video2CodeVideo:
    def __init__(self):
        self.config_dict = {
            # 原视频文件
            "input_file": "video/test.mp4",
            # 中间文件存放目录
            "cache_dir": "cache",
            # 是否保留过程文件。True--保留,False--不保留
            "save_cache_flag": False,
            # 使用使用的字符集
            "ascii_char_list": list("01B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. "),
        }

    # 第一步从函数,将像素转换为字符
    # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
    def rgb_2_char(self, r, g, b, alpha=256):
        if alpha == 0:
            return &#39;&#39;
        length = len(self.config_dict["ascii_char_list"])
        gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
        unit = (256.0 + 1) / length        return self.config_dict["ascii_char_list"][int(gray / unit)]

    # 第一步从函数,将txt转换为图片
    # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
    def txt_2_image(self, file_name):
        im = Image.open(file_name).convert(&#39;RGB&#39;)
        # gif拆分后的图像,需要转换,否则报错,由于gif分割后保存的是索引颜色
        raw_width = im.width
        raw_height = im.height
        width = int(raw_width / 6)
        height = int(raw_height / 15)
        im = im.resize((width, height), Image.NEAREST)

        txt = ""
        colors = []
        for i in range(height):
            for j in range(width):
                pixel = im.getpixel((j, i))
                colors.append((pixel[0], pixel[1], pixel[2]))
                if (len(pixel) == 4):
                    txt += self.rgb_2_char(pixel[0], pixel[1], pixel[2], pixel[3])
                else:
                    txt += self.rgb_2_char(pixel[0], pixel[1], pixel[2])
            txt += &#39;\n&#39;
            colors.append((255, 255, 255))

        im_txt = Image.new("RGB", (raw_width, raw_height), (255, 255, 255))
        dr = ImageDraw.Draw(im_txt)
        # font = ImageFont.truetype(os.path.join("fonts","汉仪楷体简.ttf"),18)
        font = ImageFont.load_default().font
        x = y = 0
        # 获取字体的宽高
        font_w, font_h = font.getsize(txt[1])
        font_h *= 1.37  # 调整后更佳
        # ImageDraw为每个ascii码进行上色
        for i in range(len(txt)):
            if (txt[i] == &#39;\n&#39;):
                x += font_h
                y = -font_w            # self, xy, text, fill = None, font = None, anchor = None,
            # *args, ** kwargs
            dr.text((y, x), txt[i], fill=colors[i])
            # dr.text((y, x), txt[i], font=font, fill=colors[i])
            y += font_w

        name = file_name        # print(name + &#39; changed&#39;)
        im_txt.save(name)


    # 第一步,将原视频转成字符图片
    # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
    def video_2_txt_jpg(self, file_name):
        vc = cv2.VideoCapture(file_name)
        c = 1
        if vc.isOpened():
            r, frame = vc.read()
            if not os.path.exists(self.config_dict["cache_dir"]):
                os.mkdir(self.config_dict["cache_dir"])
            os.chdir(self.config_dict["cache_dir"])
        else:
            r = False
        while r:
            cv2.imwrite(str(c) + &#39;.jpg&#39;, frame)
            self.txt_2_image(str(c) + &#39;.jpg&#39;)  # 同时转换为ascii图
            r, frame = vc.read()
            c += 1
        os.chdir(&#39;..&#39;)
        return vc    # 第二步,将字符图片合成新视频
    def txt_jpg_2_video(self, outfile_name, fps):
        fourcc = VideoWriter_fourcc(*"MJPG")

        images = os.listdir(self.config_dict["cache_dir"])
        im = Image.open(self.config_dict["cache_dir"] + &#39;/&#39; + images[0])
        vw = cv2.VideoWriter(outfile_name + &#39;.avi&#39;, fourcc, fps, im.size)

        os.chdir(self.config_dict["cache_dir"])
        for image in range(len(images)):
            # Image.open(str(image)+&#39;.jpg&#39;).convert("RGB").save(str(image)+&#39;.jpg&#39;)
            frame = cv2.imread(str(image + 1) + &#39;.jpg&#39;)
            vw.write(frame)
            # print(str(image + 1) + &#39;.jpg&#39; + &#39; finished&#39;)
        os.chdir(&#39;..&#39;)
        vw.release()

    # 第三步,从原视频中提取出背景音乐
    def video_extract_mp3(self, file_name):
        outfile_name = file_name.split(&#39;.&#39;)[0] + &#39;.mp3&#39;
        subprocess.call(&#39;ffmpeg -i &#39; + file_name + &#39; -f mp3 -y &#39; + outfile_name, shell=True)

    # 第四步,将背景音乐添加到新视频中
    def video_add_mp3(self, file_name, mp3_file):
        outfile_name = file_name.split(&#39;.&#39;)[0] + &#39;-txt.mp4&#39;
        subprocess.call(&#39;ffmpeg -i &#39; + file_name + &#39; -i &#39; + mp3_file + &#39; -strict -2 -f mp4 -y &#39; + outfile_name, shell=True)

    # 第五步,如果没配置保留则清除过程文件
    def clean_cache_while_need(self):
        # 为了清晰+代码比较短,直接写成内部函数
        def remove_cache_dir(path):
            if os.path.exists(path):
                if os.path.isdir(path):
                    dirs = os.listdir(path)
                    for d in dirs:
                        if os.path.isdir(path + &#39;/&#39; + d):
                            remove_cache_dir(path + &#39;/&#39; + d)
                        elif os.path.isfile(path + &#39;/&#39; + d):
                            os.remove(path + &#39;/&#39; + d)
                    os.rmdir(path)
                    return
                elif os.path.isfile(path):
                    os.remove(path)
                return
        # 为了清晰+代码比较短,直接写成内部函数
        def delete_middle_media_file():
            os.remove(self.config_dict["input_file"].split(&#39;.&#39;)[0] + &#39;.mp3&#39;)
            os.remove(self.config_dict["input_file"].split(&#39;.&#39;)[0] + &#39;.avi&#39;)
        # 如果没配置保留则清除过程文件
        if not self.config_dict["save_cache_flag"]:
            remove_cache_dir(self.config_dict["cache_dir"])
            delete_middle_media_file()

    # 程序主要逻辑
    def main_logic(self):
        # 第一步,将原视频转成字符图片
        vc = self.video_2_txt_jpg(self.config_dict["input_file"])
        # 获取原视频帧率
        fps = vc.get(cv2.CAP_PROP_FPS)
        # print(fps)
        vc.release()
        # 第二步,将字符图片合成新视频
        self.txt_jpg_2_video(self.config_dict["input_file"].split(&#39;.&#39;)[0], fps)
        print(self.config_dict["input_file"], self.config_dict["input_file"].split(&#39;.&#39;)[0] + &#39;.mp3&#39;)
        # 第三步,从原视频中提取出背景音乐
        self.video_extract_mp3(self.config_dict["input_file"])
        # 第四步,将背景音乐添加到新视频中
        self.video_add_mp3(self.config_dict["input_file"].split(&#39;.&#39;)[0] + &#39;.avi&#39;, self.config_dict["input_file"].split(&#39;.&#39;)[0] + &#39;.mp3&#39;)
        # 第五步,如果没配置保留则清除过程文件
        self.clean_cache_while_need()if __name__ == &#39;__main__&#39;:
    obj = Video2CodeVideo()
    obj.main_logic()

운영 환경:

운영 체제: win10
버전: Python 3.8.4
종속 라이브러리: pip install opencv-python Pillow
관리자 권한으로 설치했는데 내 것이 설치되었으며 다음과 같이 표시됩니다.
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

종속 애플리케이션: ffpmeg(직접 다운로드 및 압축 풀기, bin 디렉터리를 PATH 환경 변수에 추가)
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

초보자처럼 실행하세요(큰 분들은 장님인 척하세요):

위의 이름을 지정하세요 소스 코드 video_2_code_video.py, 같은 디렉터리에 새 폴더 video 만들기:
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다
변환할 원본 비디오를 video에 넣고 이름을 test.mp4로 지정합니다.
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다
Python3.8
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다
을 열고 video_2_code_video.py를 실행합니다. , 아래와 같이 실행 중입니다. Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

는 다음과 같은 중간 파일을 생성합니다.
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다
오랜 기다림 끝에 마침내 원하는 것을 얻었습니다.
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

test-txt.mp4는 코드 댄스입니다. 원하는 것:
Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다

많은 무료 학습 추천, python tutorial(동영상)

을 방문하세요.

위 내용은 Python의 Douyin Kuaishou 캐릭터 댄스를 소개합니다의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 CSDN에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
Python의 실행 모델 : 컴파일, 해석 또는 둘 다?Python의 실행 모델 : 컴파일, 해석 또는 둘 다?May 10, 2025 am 12:04 AM

pythonisbothcompiledandlandingreted.

Python은 라인별로 실행됩니까?Python은 라인별로 실행됩니까?May 10, 2025 am 12:03 AM

Python은 엄격하게 라인 별 실행이 아니지만 통역사 메커니즘을 기반으로 최적화되고 조건부 실행입니다. 통역사는 코드를 PVM에 의해 실행 된 바이트 코드로 변환하며 상수 표현식을 사전 컴파일하거나 루프를 최적화 할 수 있습니다. 이러한 메커니즘을 이해하면 코드를 최적화하고 효율성을 향상시키는 데 도움이됩니다.

파이썬에서 두 목록을 연결하는 대안은 무엇입니까?파이썬에서 두 목록을 연결하는 대안은 무엇입니까?May 09, 2025 am 12:16 AM

Python에는 두 개의 목록을 연결하는 방법이 많이 있습니다. 1. 연산자 사용 간단하지만 큰 목록에서는 비효율적입니다. 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 효율적이고 읽기 쉬운 = 연산자를 사용하십시오. 4. 메모리 효율적이지만 추가 가져 오기가 필요한 itertools.chain function을 사용하십시오. 5. 우아하지만 너무 복잡 할 수있는 목록 구문 분석을 사용하십시오. 선택 방법은 코드 컨텍스트 및 요구 사항을 기반으로해야합니다.

파이썬 : 두 목록을 병합하는 효율적인 방법파이썬 : 두 목록을 병합하는 효율적인 방법May 09, 2025 am 12:15 AM

Python 목록을 병합하는 방법에는 여러 가지가 있습니다. 1. 단순하지만 큰 목록에 대한 메모리 효율적이지 않은 연산자 사용; 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 큰 데이터 세트에 적합한 itertools.chain을 사용하십시오. 4. 사용 * 운영자, 한 줄의 코드로 중소형 목록을 병합하십시오. 5. Numpy.concatenate를 사용하십시오. 이는 고성능 요구 사항이있는 대규모 데이터 세트 및 시나리오에 적합합니다. 6. 작은 목록에 적합하지만 비효율적 인 Append Method를 사용하십시오. 메소드를 선택할 때는 목록 크기 및 응용 프로그램 시나리오를 고려해야합니다.

편집 된 vs 해석 언어 : 장단점편집 된 vs 해석 언어 : 장단점May 09, 2025 am 12:06 AM

CompiledLanguagesOfferSpeedSecurity, while InterpretedLanguagesProvideeaseofusEandportability

파이썬 : 가장 완전한 가이드 인 루프를 위해파이썬 : 가장 완전한 가이드 인 루프를 위해May 09, 2025 am 12:05 AM

Python에서, for 루프는 반복 가능한 물체를 가로 지르는 데 사용되며, 조건이 충족 될 때 반복적으로 작업을 수행하는 데 사용됩니다. 1) 루프 예제 : 목록을 가로 지르고 요소를 인쇄하십시오. 2) 루프 예제 : 올바르게 추측 할 때까지 숫자 게임을 추측하십시오. 마스터 링 사이클 원리 및 최적화 기술은 코드 효율성과 안정성을 향상시킬 수 있습니다.

Python은 문자열로 나열됩니다Python은 문자열로 나열됩니다May 09, 2025 am 12:02 AM

목록을 문자열로 연결하려면 Python의 join () 메소드를 사용하는 것이 최선의 선택입니다. 1) join () 메소드를 사용하여 목록 요소를 ''.join (my_list)과 같은 문자열로 연결하십시오. 2) 숫자가 포함 된 목록의 경우 연결하기 전에 맵 (str, 숫자)을 문자열로 변환하십시오. 3) ','. join (f '({fruit})'forfruitinfruits와 같은 복잡한 형식에 발전기 표현식을 사용할 수 있습니다. 4) 혼합 데이터 유형을 처리 할 때 MAP (str, mixed_list)를 사용하여 모든 요소를 ​​문자열로 변환 할 수 있도록하십시오. 5) 큰 목록의 경우 ''.join (large_li

Python의 하이브리드 접근법 : 컴파일 및 해석 결합Python의 하이브리드 접근법 : 컴파일 및 해석 결합May 08, 2025 am 12:16 AM

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.