つまりなにしたの?
OpenCVでiMovieから直接読み込める動画を出力するためには、XVIDではなくmp4vを使う。
OpenCVで色々作ってみているものの、結果をまとめてYoutubeに上げる時にiMovieを使っている。
エンコーダとかで適当に変換しても良いんだけど、最初から使える方式で書き出すに越したことがないので覚書として書いておく。
*1
FourCCの設定
基本的に今日の話はここの設定を何にすれば直接iMovieで扱えるかって話になる。
www.fourcc.org
FourCC codeを設定すると4バイトのコードでビデオコーデックを指定できる。
OpenCVのサンプル
OpenCVのサンプルだとXVIDが指定されていて推奨されているように書いてあるからついこれで書き出してしまった。
OpenCV: Getting Started with Videos
import numpy as np import cv2 as cv cap = cv.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv.VideoWriter_fourcc(*'XVID') out = cv.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv.flip(frame,0) # write the flipped frame out.write(frame) cv.imshow('frame',frame) if cv.waitKey(1) & 0xFF == ord('q'): break else: break # Release everything if job is finished cap.release() out.release() cv.destroyAllWindows()
で、出てきたoutput.aviをiMovieにドラッグ・アンド・ドロップしたら、ダメだよって怒られた。
どうすればいいか
そこで書き換えたのがこちら。fourccの設定をmp4vにする。
import cv2 """Capture video from camera""" # カメラをキャプチャする cap = cv2.VideoCapture(0) ret, frame = cap.read() height, width = frame.shape[:2] fps = 30 # 出力先のファイルを開く fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter('output.mp4', int(fourcc), fps, (int(width), int(height))) while True: ret, frame = cap.read() cv2.imshow('camera capture', frame) out.write(frame) k = cv2.waitKey(10) # 10msec待つ if k == 27: # ESCキーで終了 break # 解放する cap.release() out.release() cv2.destroyAllWindows()
*1:結構時間のかかる書き出しをしていたのに直接読み出せなくて泣きたくなった