37
30

More than 5 years have passed since last update.

Python3+OpenCVで静止画から動画を作成する

Last updated at Posted at 2018-08-04

Python3+OpenCVで複数枚の連続した静止画を作成し、動画にしてみた。

実行内容

imgs.png

連続した静止画ファイルを作成し、MP4形式の動画ファイルへ変換

環境

環境
PC Ubuntu 16.04 LTS
言語 Python 3.6.6
ライブラリ opencv-3.4.2.17, numpy-1.15.0

静止画・動画の作成プログラム

genImgVideo.py
import os
import cv2
import numpy as np

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

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))
        img.fill(255)

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

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

        outimg_files.append(outimg_file)

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

for img_file in outimg_files:
    img = cv2.imread(img_file)
    video.write(img)

video.release()

MP4形式で以下のような動画が出力される (ImgVideo.mp4)
ImgVideo.gif

37
30
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
37
30