LoginSignup
2
2

More than 1 year has passed since last update.

OpenCVとPillowで画像データに取得日時を書き込み

Last updated at Posted at 2021-06-07

画像データ(フォルダ内の一連のjpegファイル)をモノクロ化して取得日時を書き込み、別のフォルダに出力します。
ファイルのプロパティを見ると、「変更日時」が取得日時に相当していたので、こちらのコードからちょっと変えます。
Windows 10、Python 3.8.5で実行しました。
英数字だけを書き込んでいますが、OpenCVのデフォルトのフォントではなくArialを使いたかったので、日本語の書き込み方を参考にしました。

Python
import cv2 as cv
import numpy as np
import PIL
from PIL import ImageFont, ImageDraw, Image
import os
import glob
import datetime

# 出力先フォルダを指定
output_path = './output/'

# ファイルの変更日時を取得
def get_exif(image_path):
    t = os.path.getmtime(image_path)
    d = datetime.datetime.fromtimestamp(t)
    captured_datetime = d.strftime("%Y/%m/%d %H:%M:%S")
    return captured_datetime

# 各ファイルに変更日時を書き込む
def write_text(input_path):
    captured_datetime = get_exif(input_path)
    image_name = os.path.split(input_path)[1]
    img = cv.imread(input_path)

    # モノクロ化
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    # 文字入れ
    fontpath ='C:/Windows/Fonts/arialbd.ttf' #Arial Bold
    font = ImageFont.truetype(fontpath, 64) # フォントサイズ64

    # 表示位置:画像に合わせて調整
    position = (30, 1820)

    img_pil = Image.fromarray(img_gray)
    draw = ImageDraw.Draw(img_pil)
    draw.text(position, captured_datetime, font = font , fill = 255) # fill = 255で白

    img_gray = np.array(img_pil) # PIL を配列に変換
    cv.imwrite(os.path.join(output_path, image_name), img_gray) # ファイル名は同じ

# 元フォルダから一括変換
# 一括変換する前に1枚テストしてフォントサイズや位置を確認しましょう
for f in glob.glob('./input/*.jpg'):
    write_text(f)

出力結果イメージ

文字部分だけ切り取っています。
output.png

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2