LoginSignup
18
27

More than 3 years have passed since last update.

Python3+OpenCVを使って連番画像から動画を作る

Last updated at Posted at 2019-07-03

はじめに

連番画像から動画を作りたかったが、色々ハマったので自分用にメモ

環境

  • Python 3.6.3
  • OpenCV 4.1.0
  • numpy 1.16.2

現象

  • 画像の大きさがあっていないとmp4を書き出すことはできるものの、異常にファイルサイズが小さく再生できなかった。
  • 画像の大きさを前もって調べてコードの中に書いておき、画像が全て同じ大きさでない場合はリサイズして揃えておかなければならない。

画像の大きさが違っててリサイズしたい場合

画像のリサイズを行うときは

img = cv2.resize(img, (640,480))

とする。

img.resize(640,480)

のようにしているサイトを参考にしたため、動画が作成できなかった。
あまり大きいサイズの画像をリサイズするとout of memoryになったので
前もって大きさを変えた方がいいかもしれない。

コード

import sys
import cv2

# encoder(for mp4)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
# output file name, encoder, fps, size(fit to image size)
video = cv2.VideoWriter('video.mp4',fourcc, 20.0, (1240, 1360))

if not video.isOpened():
    print("can't be opened")
    sys.exit()

for i in range(0, 90+1):
    # hoge0000.png, hoge0001.png,..., hoge0090.png
    img = cv2.imread('./hoge%04d.png' % i)

    # can't read image, escape
    if img is None:
        print("can't read")
        break

    # add
    video.write(img)
    print(i)

video.release()
print('written')
18
27
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
18
27