Python實現(xiàn)抖音快手字符舞的示例-創(chuàng)新互聯(lián)

這篇文章給大家分享的是有關(guān)Python實現(xiàn)抖音快手字符舞的示例的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)為客戶提供專業(yè)的網(wǎng)站設(shè)計、網(wǎng)站制作、程序、域名、空間一條龍服務(wù),提供基于WEB的系統(tǒng)開發(fā). 服務(wù)項目涵蓋了網(wǎng)頁設(shè)計、網(wǎng)站程序開發(fā)、WEB系統(tǒng)開發(fā)、微信二次開發(fā)、移動網(wǎng)站建設(shè)等網(wǎng)站方面業(yè)務(wù)。


字符舞:

代碼舞

源代碼:

video_2_code_video.py

import argparseimport osimport cv2import subprocessfrom cv2 import VideoWriter_fourccfrom PIL import Image, ImageFont, ImageDraw# 命令行輸入?yún)?shù)處理# 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文件,默認(rèn)不保存class Video2CodeVideo:
    def __init__(self):
        self.config_dict = {
            # 原視頻文件
            "input_file": "video/test.mp4",
            # 中間文件存放目錄
            "cache_dir": "cache",
            # 是否保留過程文件。True--保留,F(xiàn)alse--不保留
            "save_cache_flag": False,
            # 使用使用的字符集
            "ascii_char_list": list("01B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. "),
        }

    # 第一步從函數(shù),將像素轉(zhuǎn)換為字符
    # 調(diào)用棧:video_2_txt_jpg -> txt_2_image -> rgb_2_char
    def rgb_2_char(self, r, g, b, alpha=256):
        if alpha == 0:
            return ''
        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)]

    # 第一步從函數(shù),將txt轉(zhuǎn)換為圖片
    # 調(diào)用棧:video_2_txt_jpg -> txt_2_image -> rgb_2_char
    def txt_2_image(self, file_name):
        im = Image.open(file_name).convert('RGB')
        # gif拆分后的圖像,需要轉(zhuǎn)換,否則報錯,由于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 += '\n'
            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  # 調(diào)整后更佳
        # ImageDraw為每個ascii碼進(jìn)行上色
        for i in range(len(txt)):
            if (txt[i] == '\n'):
                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 + ' changed')
        im_txt.save(name)


    # 第一步,將原視頻轉(zhuǎn)成字符圖片
    # 調(diào)用棧: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) + '.jpg', frame)
            self.txt_2_image(str(c) + '.jpg')  # 同時轉(zhuǎn)換為ascii圖
            r, frame = vc.read()
            c += 1
        os.chdir('..')
        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"] + '/' + images[0])
        vw = cv2.VideoWriter(outfile_name + '.avi', fourcc, fps, im.size)

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

    # 第三步,從原視頻中提取出背景音樂
    def video_extract_mp3(self, file_name):
        outfile_name = file_name.split('.')[0] + '.mp3'
        subprocess.call('ffmpeg -i ' + file_name + ' -f mp3 -y ' + outfile_name, shell=True)

    # 第四步,將背景音樂添加到新視頻中
    def video_add_mp3(self, file_name, mp3_file):
        outfile_name = file_name.split('.')[0] + '-txt.mp4'
        subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 -y ' + outfile_name, shell=True)

    # 第五步,如果沒配置保留則清除過程文件
    def clean_cache_while_need(self):
        # 為了清晰+代碼比較短,直接寫成內(nèi)部函數(shù)
        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 + '/' + d):
                            remove_cache_dir(path + '/' + d)
                        elif os.path.isfile(path + '/' + d):
                            os.remove(path + '/' + d)
                    os.rmdir(path)
                    return
                elif os.path.isfile(path):
                    os.remove(path)
                return
        # 為了清晰+代碼比較短,直接寫成內(nèi)部函數(shù)
        def delete_middle_media_file():
            os.remove(self.config_dict["input_file"].split('.')[0] + '.mp3')
            os.remove(self.config_dict["input_file"].split('.')[0] + '.avi')
        # 如果沒配置保留則清除過程文件
        if not self.config_dict["save_cache_flag"]:
            remove_cache_dir(self.config_dict["cache_dir"])
            delete_middle_media_file()

    # 程序主要邏輯
    def main_logic(self):
        # 第一步,將原視頻轉(zhuǎn)成字符圖片
        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('.')[0], fps)
        print(self.config_dict["input_file"], self.config_dict["input_file"].split('.')[0] + '.mp3')
        # 第三步,從原視頻中提取出背景音樂
        self.video_extract_mp3(self.config_dict["input_file"])
        # 第四步,將背景音樂添加到新視頻中
        self.video_add_mp3(self.config_dict["input_file"].split('.')[0] + '.avi', self.config_dict["input_file"].split('.')[0] + '.mp3')
        # 第五步,如果沒配置保留則清除過程文件
        self.clean_cache_while_need()if __name__ == '__main__':
    obj = Video2CodeVideo()
    obj.main_logic()

運行環(huán)境:

操作系統(tǒng):win10
版本:Python 3.8.4
依賴庫:pip install opencv-python pillow
管理員權(quán)限安裝,我的已安裝過,顯示這樣:
Python實現(xiàn)抖音快手字符舞的示例

依賴應(yīng)用: ffpmeg(下載直接解壓、將bin目錄加到PATH環(huán)境變量)
Python實現(xiàn)抖音快手字符舞的示例

小白式運行(大佬請裝瞎):

將上面的源代碼命名video_2_code_video.py,在同一目錄下新建文件夾video:
Python實現(xiàn)抖音快手字符舞的示例
在video中放入要轉(zhuǎn)換的原視頻,命名test.mp4:
Python實現(xiàn)抖音快手字符舞的示例
打開Python3.8
Python實現(xiàn)抖音快手字符舞的示例
運行video_2_code_video.py,如下圖顯示表示正在運行:Python實現(xiàn)抖音快手字符舞的示例

會產(chǎn)生一些中間文件諸如:
Python實現(xiàn)抖音快手字符舞的示例
Python實現(xiàn)抖音快手字符舞的示例
經(jīng)過漫長的等待,終于得償所愿:
Python實現(xiàn)抖音快手字符舞的示例

test-txt.mp4就是所要的代碼舞啦:
Python實現(xiàn)抖音快手字符舞的示例

感謝各位的閱讀!關(guān)于“Python實現(xiàn)抖音快手字符舞的示例”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

標(biāo)題名稱:Python實現(xiàn)抖音快手字符舞的示例-創(chuàng)新互聯(lián)
當(dāng)前路徑:http://muchs.cn/article2/ijjic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、動態(tài)網(wǎng)站、企業(yè)網(wǎng)站制作靜態(tài)網(wǎng)站App設(shè)計、小程序開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)