Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created August 8, 2023 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kujirahand/ae466b3c2168ff7430d353d1dcc8609b to your computer and use it in GitHub Desktop.
Save kujirahand/ae466b3c2168ff7430d353d1dcc8609b to your computer and use it in GitHub Desktop.
画像にロゴを重ねるプログラム
import imageio, glob, os
from PIL import Image
import numpy as np
# ロゴファイルや入出力フォルダを指定 --- (*1)
LOGO_FILE = './logo.png' # ロゴ
INPUT_DIR = './in_dir' # 入力フォルダ
OUTPUT_DIR = './out_dir' # 出力フォルダ
# 背景透過したロゴを読み込む --- (*2)
logo = Image.open(LOGO_FILE)
logo = logo.convert("RGBA") # RGBAモードに変換
logo_width, logo_height = logo.size
# メインプログラム --- (*3)
def main():
# 入力フォルダにある動画一覧を得る
files = glob.glob(f'{INPUT_DIR}/*.mp4')
# 動画ファイルを一つずつ処理する
for idx, infile in enumerate(files):
print(f'{idx:003}:{infile}')
outfile = os.path.join(OUTPUT_DIR, os.path.basename(infile))
add_logo_to_video(infile, outfile)
print("ok")
# 動画にロゴを追加する関数 --- (*4)
def add_logo_to_video(infile, outfile):
# 動画を読み込む --- (*5)
reader = imageio.get_reader(infile)
fps = reader.get_meta_data()['fps']
# 出力動画の書き込みを開始 --- (*6)
writer = imageio.get_writer(outfile, fps=fps)
# 動画の各フレームにロゴを描画して書き込む --- (*7)
for i, frame in enumerate(reader):
# フレームをPillowのImageオブジェクトに変換
frame_image = Image.fromarray(frame)
if i == 0:
# ロゴをframe_imageの1/3のサイズにリサイズ --- (*8)
target_width = int(frame_image.width / 3)
aspect_ratio = logo.width / logo.height
target_height = int(target_width / aspect_ratio)
resized_logo = logo.resize((target_width, target_height))
# ロゴの位置を右上にする --- (*9)
position = (frame_image.width - resized_logo.width - 20, 50)
# フレームとロゴを合成 --- (*10)
frame_image.paste(resized_logo, position, resized_logo)
# Imageオブジェクトをnumpy配列に変換して書き込み --- (*11)
writer.append_data(np.array(frame_image))
writer.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment