【Python】動画からGIFをつくる の続き。
GIF Maker - Video to GIF Creator Tools | GIPHY に少しでも近づけるようにテキストをつけられるようにした。
コード
追加したコード
from collections import namedtuple
from PIL import ImageDraw, ImageFont
# テキスト関連のデータまとめ用のタプル
Cc = namedtuple("Cc", [
"start_index",
"stop_index",
"text",
"font",
"rgba",
"point"
])
def make_cc(gif_fps, start_sec, stop_sec, text, font, rgba, point):
start_index = start_sec * gif_fps
stop_index = stop_sec * gif_fps
return Cc(start_index, stop_index, text, font, rgba, point)
def add_text_to_image(im_list, cc_list):
new_im_list = []
for index, im_obj in enumerate(im_list):
new_im = None
for cc in cc_list:
if index >= cc.start_index and index <= cc.stop_index:
if new_im is None:
new_im = add_text_to_image_object(im_obj, cc)
else:
new_im = add_text_to_image_object(new_im, cc)
if new_im is None:
new_im_list.append(im_obj)
else:
new_im_list.append(new_im)
return new_im_list
def add_text_to_image_object(im_obj, cc):
base = im_obj.convert('RGBA')
# make a blank image for the text, initialized to transparent text color
text_img = Image.new('RGBA', base.size, (255,255,255,0))
# get a drawing context
d = ImageDraw.Draw(text_img)
# draw text
d.text(cc.point, cc.text, font=cc.font, fill=cc.rgba)
out = Image.alpha_composite(base, text_img)
return out
メイン処理
def main():
"""メイン処理"""
video_file = "Wildlife.wmv"
fps, count = get_fps_n_count(video_file)
if fps is None:
print("動画ファイルを開けませんでした")
return
# gifにしたい範囲を指定
start_sec = 0
stop_sec = 8
start_frame = int(start_sec * fps)
stop_frame = int(stop_sec * fps)
step_frame = 3
print("開始(けっこう時間がかかる)")
im_list = get_frame_range(video_file, start_frame, stop_frame, step_frame)
if im_list is None:
print("動画ファイルを開けませんでした")
return
# テキスト関連の処理
gif_fps = len(im_list) // (stop_sec - start_sec)
font1 = ImageFont.truetype(font=r"C:\Windows\Fonts\meiryo.ttc", size=32)
font2 = ImageFont.truetype(font=r"C:\Windows\Fonts\BAUHS93.TTF", size=32)
cc1 = make_cc(gif_fps, 0, 2, "あいうえお", font1, (255, 0, 0, 255), (5, 5))
cc2 = make_cc(gif_fps, 1, 3, "ABCDE", font2, (0, 255, 0, 255), (5, 50))
cc3 = make_cc(gif_fps, 2, 4, "かきくけこ", font1, (0, 0, 255, 255), (5, 100))
cc4 = make_cc(gif_fps, 3, 5, "FGHIJ", font2, (255, 255, 255, 255), (5, 150))
new_im_list = add_text_to_image(im_list, [cc1, cc2, cc3, cc4])
make_gif('どうぶつ2.gif', new_im_list)
print("終了")
出来たGIF
参考
おわり