fkeiwkblog

日記や、今時のAIの餌(学習の)を生産してます。プログラムライブラリなど

【Python】静止画像を表示させながら、字幕を表示するスクリプトを作る

静止画像を表示させながら、字幕を表示するスクリプトの作成しました。

windows10対応しており、 python言語を使いました

フォントは、Windows 10標準の「BIZ-UDMinchoM.ttc」を使用しています。

必要なpython パッケージをまとめてインストール

次のpipコマンドを使ってまとめてインストールを完了してください.

pip install opencv-python numpy pyttsx3 Pillow

本題のソースを書く

import cv2
import numpy as np
import pyttsx3
from PIL import ImageFont, ImageDraw, Image

def create_subtitled_video(image_path, text, font_path, font_size=36, fps=10):
    # 文章を読み上げる関数を定義
    def speak(text):
        engine = pyttsx3.init()
        engine.setProperty('rate', 150)
        engine.say(text)
        engine.runAndWait()

    # 静止画を読み込み
    img = cv2.imread(image_path)

    # フォントを設定
    font = ImageFont.truetype(font_path, font_size)

    # 文章を読み上げ、同時に静止画に字幕を表示する動画を作成
    out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, (img.shape[1], img.shape[0]))
    speak(text)
    for i in range(fps):
        pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(pil_img)
        draw.text((50, 50), text, font=font, fill=(0, 255, 0))
        img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
        out.write(img)
    out.release()

この関数の使い方

この関数を呼び出す際には、以下のように引数を指定してください。

image_path: 静止画のパス text: 字幕に表示する文章 font_path: 日本語フォントのパス font_size (オプション): フォントサイズ (デフォルト値: 36) fps (オプション): 動画のフレームレート (デフォルト値: 10) 例えば、以下のように呼び出すことができます。

image_path = 'image.jpg'
text = 'PythonでOpenCVを使って、静止画を表示させながら文章を合成音声で読み上げ、字幕が表示される動画を作成します。'
font_path = r'C:\Windows\Fonts\BIZ-UDMinchoM.ttc'
create_subtitled_video(image_path, text, font_path)

クラス化もしてみた

import cv2
import numpy as np
import pyttsx3
from PIL import ImageFont, ImageDraw, Image

class SubtitledVideo:
    def __init__(self, image_path, font_path, font_size=36, fps=10):
        self.image_path = image_path
        self.font_path = font_path
        self.font_size = font_size
        self.fps = fps

    def _speak(self, text):
        engine = pyttsx3.init()
        engine.setProperty('rate', 150)
        engine.say(text)
        engine.runAndWait()

    def create(self, text):
        # 静止画を読み込み
        img = cv2.imread(self.image_path)

        # フォントを設定
        font = ImageFont.truetype(self.font_path, self.font_size)

        # 文章を読み上げ、同時に静止画に字幕を表示する動画を作成
        out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), self.fps, (img.shape[1], img.shape[0]))
        self._speak(text)
        for i in range(self.fps):
            pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
            draw = ImageDraw.Draw(pil_img)
            draw.text((50, 50), text, font=font, fill=(0, 255, 0))
            img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
            out.write(img)
        out.release()

SubtitledVideo クラスを利用する場合は、以下のようにインスタンスを作成し、create() メソッドに表示したい文字列を渡して呼び出します。

その使い方

image_path = 'image.jpg'
font_path = r'C:\Windows\Fonts\BIZ-UDMinchoM.ttc'
text = 'PythonでOpenCVを使って、静止画を表示させながら文章を合成音声で読み上げ、字幕が表示される動画を作成します。'

video = SubtitledVideo(image_path, font_path)
video.create(text)

init() メソッドの引数については、以下の通りです。

image_path: 静止画のパス font_path: 日本語フォントのパス font_size (オプション): フォントサイズ (デフォルト値: 36) fps (オプション): 動画のフレームレート (デフォルト値: 10) create() メソッドの引数については、表示する文字列を渡してください。

最後に

 本記事はchatgdpにより、作成時間を短縮できました。この機能を使ってより良質なコンテンツを作成できるよう努めます。
 また、プログラム系は使えるか確認する必要があるため、使えるとことを確認してから載せます。そのためchatgdpで質問を重ねるよりも、より迅速に答えにありつける可能性があるため、当記事に価値があると考え発信しました。