【python3】將視頻轉換為代碼視頻


一、環境准備

       1、需要安裝opencv,直接安裝 pip install opencv-python

  2、需要安裝ffmpeg ,直接解壓免安裝,下載傳送門; 將 ffmpeg.exe 的路徑復制,替換代碼開頭的  ffmpeg = r'G:\ffmpeg\bin\ffmpeg.exe‘  

  3、源碼參考自 https://blog.csdn.net/kongfu_cat/article/details/79681719?utm_source=copy ,對其修改了一下,並增加了視頻截取和顏色選擇的功能,親測可用。

二、源代碼

# -*- coding:utf-8 -*-
# coding:utf-8
import os, cv2, subprocess, shutil
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
from PIL import Image, ImageFont, ImageDraw

ffmpeg = r'D:\ffmpeg\bin\ffmpeg.exe'
code_color = (169,169,169) # 顏色RGB 默認灰色 ,'' 則彩色

# 像素對應ascii碼
#ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. ")
#ascii_char = ['.',',',':',';','+','*','?','%','S','#','@'][::-1]
#ascii_char = list("MNHQ$OC67+>!:-. ")
ascii_char = list("MNHQ$OC67)oa+>!:+. ")

# 將像素轉換為ascii碼
def get_char(r, g, b, alpha=256):
    if alpha == 0:
        return ''
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]

# 將txt轉換為圖片
def txt2image(file_name):
    im = Image.open(file_name).convert('RGB')
    # 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 += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
            else:
                txt += get_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  # 調整后更佳
    # ImageDraw為每個ascii碼進行上色
    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
        if code_color:
            dr.text((y, x), txt[i], fill=code_color) # fill=colors[i]彩色
        else:
            dr.text((y, x), txt[i], fill=colors[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)

# 將視頻拆分成圖片
def video2txt_jpg(file_name):
    vc = cv2.VideoCapture(file_name)
    c = 1
    if vc.isOpened():
        r, frame = vc.read()
        if not os.path.exists('Cache'):
            os.mkdir('Cache')
        os.chdir('Cache')
    else:
        r = False
    while r:
        cv2.imwrite(str(c) + '.jpg', frame)
        txt2image(str(c) + '.jpg')  # 同時轉換為ascii圖
        r, frame = vc.read()
        c += 1
    os.chdir('..')
    return vc

# 將圖片合成視頻
def jpg2video(outfile_name, fps):
    fourcc = VideoWriter_fourcc(*"MJPG")
    images = os.listdir('Cache')
    im = Image.open('Cache/' + images[0])
    vw = cv2.VideoWriter(outfile_name, fourcc, fps, im.size)

    os.chdir('Cache')
    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()

# 調用ffmpeg獲取mp3音頻文件
def video2mp3(file_name, outfile_name):
    cmdstr = " -i {0} -f mp3 {1} -y".format(file_name, outfile_name)
    cmd(cmdstr)

# 合成音頻和視頻文件
def video_add_mp3(file_name, mp3_file,outfile_name):
    cmdstr = " -i {0} -i {1} -strict -2 -f mp4 {2} -y".format(file_name, mp3_file, outfile_name)
    cmd(cmdstr)

# 視頻截取
def vediocut(file_name, outfile_name, start, end):
    cmdstr = " -i {0} -vcodec copy -acodec copy -ss {1} -to {2} {3} -y".format(file_name,start,end,outfile_name)
    cmd(cmdstr)

# 執行腳本命令
def cmd(cmdstr):
    cmdstr = ffmpeg + cmdstr
    response = subprocess.call(cmdstr, shell=True, creationflags=0x08000000)
    if response == 1:
        print("ffmpeg腳本執行失敗,請嘗試手動執行:{0}".format(cmdstr))

# 主函數
def main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14'):
    """
    :param vedio: 原視頻文件地址
    :param save: 是否保存臨時文件 默認不保存
    :param iscut: 是否先對原視頻做截取處理 默認不截取
    :param start: 視頻截取開始時間點 僅當iscut=True時有效
    :param end: 視頻截取結束時間點 僅當iscut=True時有效
    :return: 輸出目標視頻文件 vedio.split('.')[0] + '-code.mp4'
    """
    file_cut = vedio.split('.')[0] + '_cut.mp4'
    file_mp3 = vedio.split('.')[0] + '.mp3'
    file_temp_avi = vedio.split('.')[0] + '_temp.avi'
    outfile_name = vedio.split('.')[0] + '-code.mp4'
    print("開始生成...")
    if iscut:
        print("正在截取視頻...")
        vediocut(vedio, file_cut, start, end)
        vedio = file_cut
    print("正在轉換代碼圖片...")
    vc = video2txt_jpg(vedio) # 視頻轉圖片,圖片轉代碼圖片
    FPS = vc.get(cv2.CAP_PROP_FPS)  # 獲取幀率
    vc.release()
    print("正在分離音頻...")
    video2mp3(vedio, file_mp3)  # 從原視頻分離出 音頻mp3
    print("正在轉換代碼視頻...")
    jpg2video(file_temp_avi, FPS)  #代碼圖片轉視頻
    print("正在合成目標視頻...")
    video_add_mp3(file_temp_avi, file_mp3, outfile_name) # 將音頻合成到代碼視頻
    if (not save): # 移除臨時文件
        print("正在移除臨時文件...")
        shutil.rmtree("Cache")
        for file in [file_cut, file_mp3, file_temp_avi]:
            if os.path.exists(file):
                os.remove(file)
    print("生成成功:{0}".format(outfile_name))

if __name__ == '__main__':
    vedio = r"test.mp4"
    main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM