天天看點

看程式員如何使用Python快速給視訊添加字幕

# coding=utf-8

import matplotlib.pyplot as plt
from PIL import Image,ImageDraw,ImageFont

bg_size = (1920,1080)
bg_color = (0,0,0)
font_file = "C:/Users/wangle/AppData/Local/Microsoft/Windows/Fonts/漢儀雅酷黑W.ttf" #方正粗圓_GBK
font_size = 65
contex_color = (255,255,255)
height_ratio = 0.9

def gen(index,contex):
    if index / 1000 >= 1:
        index = str(index)
    elif index / 100 >= 1:
        index = '0' + str(index)
    elif index / 10 >= 1:
        index = '00' + str(index)
    else:
        index = '000' + str(index)
    
    img = Image.new(mode = "RGB", size = bg_size, color = bg_color)
    draw = ImageDraw.Draw(img, mode = "RGB")
    font = ImageFont.truetype(font_file, size = font_size)
    text_width = font.getsize(contex)
    text_coordinate = int((bg_size[0]-text_width[0]) * 0.5), int((bg_size[1]-text_width[1])* height_ratio)
    draw.text(text_coordinate, contex, contex_color, font=font)

    img = img.convert('RGBA')
    L,H = img.size
    color_0 = img.getpixel((0,0))
    for h in range(H):
        for l in range(L):
            dot = (l,h)
            color_1 = img.getpixel(dot)
            if color_1 == color_0:
                color_1 = color_1[:-1] + (0,)
                img.putpixel(dot,color_1)

    img.save('E:/vlog/第八期/subtitle/%s_%s.png' % (index,contex),'png')
    img.show()

with open('E:/vlog/第八期/20200319_165611.txt','r',encoding='utf8') as f:
    for i,text in enumerate( f.readlines()):
        text = text.strip()
        if text:
            gen(i,text)
        if i > 7:
            break      

根據txt檔案:

看程式員如何使用Python快速給視訊添加字幕

生成背景顔色透明的圖檔 圖檔下方含文字:

看程式員如何使用Python快速給視訊添加字幕
看程式員如何使用Python快速給視訊添加字幕