Python 画像への描画メモ

import os
import cv2
import numpy as np
from pathlib import Path

IMG_SIZE = 256  # 画像サイズ
BLOCK_SIZE = 32  # 黒ブロックサイズ

os.chdir(Path(__file__).resolve().parent)

img_outdir = "./img"
os.makedirs(img_outdir, exist_ok=True)

# 動画用の画像作成
outimg_files = []
img_count = 0
for h in range(0, IMG_SIZE, BLOCK_SIZE):
    for w in range(0, IMG_SIZE, BLOCK_SIZE):
        img_count = img_count + 1

        # IMG_SIZE x IMG_SIZEの白塗り画像作成
        img = np.empty((IMG_SIZE, IMG_SIZE), dtype=np.uint8)
        img.fill(255)

        # 黒ブロックを白塗り画像に書き込み
        img[h : h + BLOCK_SIZE, w : w + BLOCK_SIZE] = np.zeros((BLOCK_SIZE, BLOCK_SIZE))

        temp_img = np.zeros((IMG_SIZE, IMG_SIZE, 3))
        # draw rectangle
        temp_img = cv2.rectangle(temp_img, (50, 50), (100, 100), (0, 0, 255))
        # draw text
        temp_img = cv2.putText(
            temp_img,
            "test",
            (40, 40),
            cv2.FONT_HERSHEY_SIMPLEX,
            fontScale=0.5,
            color=(0, 255, 0),
            thickness=1,
        )

        temp_img = temp_img.astype(np.uint8)
        temp_img = np.max(temp_img, axis=2)
        print(f"temp_img.shape:{temp_img.shape}")
        img_3d = np.zeros((IMG_SIZE, IMG_SIZE, 3))
        img_3d[:, :, 0] = img
        img_3d[:, :, 1] = img
        img_3d[:, :, 2] = img
        print(f"img_3d.shape:{img_3d.shape}")
        temp_img = np.expand_dims(temp_img, -1)
        # textのところだけ赤に
        imgout = np.where(temp_img == 255, [0, 0, 255], img_3d)
        print(f"imgout.shape:{imgout.shape}")

        # 画像出力
        outimg_file = "{}/{:05d}.png".format(img_outdir, img_count)
        cv2.imwrite(outimg_file, imgout)

        print(img.shape)
        print(img.dtype)
        outimg_files.append(outimg_file)

# 動画作成
fourcc = cv2.VideoWriter_fourcc("m", "p", "4", "v")
video = cv2.VideoWriter("ImgVideo.mp4", fourcc, 5, (IMG_SIZE, IMG_SIZE))

for img_file in outimg_files:
    img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
    print(img.shape)
    print(img.dtype)
    video.write(img)

video.release()

この記事が気に入ったらサポートをしてみませんか?