LoginSignup
15
20

More than 3 years have passed since last update.

Google Colaboratoryで動画処理(初級編)

Last updated at Posted at 2019-07-20

Google Colaboratoryでは、ffmpegPIL(Pillow)、Google Driveの機能を利用できるので、研究用の動画解析/編集を簡単に実行できる。ローカルマシンのマシンパワーを消費することもないし、他の人と共同作業したり出力結果を共有することも可能で、なかなかに良い。

事前準備

動画ファイルをGoogle Driveにアップロードする

動画ファイルをGoogle Driveにアップロードする。今回は「マイドライブ/videoexp/SampleVideo_1280x720_5mb.mp4」というファイル名でアップロードした。

Screen Shot 2019-07-20 at 17.27.30.png

今回の動画ファイルはSample Videosから拝借した。

Google Driveをマウントする

from google.colab import drive
drive.mount('/content/gdrive')

ffmpegを使って、画像に変換する

ffmpegを使って、動画ファイルから画像を抽出する。抽出の際にはフレームレート(fps)を指定する。fpsは目的に応じて調整する。ここでは1fps(1秒に1フレーム)を指定している。fpsが大きくなればなるほど出力結果はスムーズになるが、その分処理の時間とファイルサイズが増大する。

import os

src_img_dir = "/content/gdrive/My Drive/videoexp/src"

if not os.path.exists(src_img_dir):
    os.makedirs(src_img_dir)

!ffmpeg -i "/content/gdrive/My Drive/videoexp/SampleVideo_1280x720_5mb.mp4" -vf fps=1 "$src_img_dir/%04d.jpg"

抽出された画像をsrcディレクトリに保存するようにしている。Google Driveでsrcディレクトリを開けば、抽出された画像の内容を確認することができる。

Screen Shot 2019-07-20 at 17.37.29.png

抽出された画像の一覧を取得する

import glob

src_files = glob.glob("{}/*.jpg".format(src_img_dir))
src_files.sort()

print(len(src_files), "image files")

一枚ずつ画像処理を行う

得られた各フレームの画像に対して、一枚ずつ処理をしていく。
ここではPILを使って「画像の右上にフレーム番号を書く」という処理を実行している。

from PIL import Image
from PIL import ImageDraw

dst_img_dir = "/content/gdrive/My Drive/videoexp/dst"
if not os.path.exists(dst_img_dir):
    os.makedirs(dst_img_dir)

for i, file in enumerate(src_files):
  im = Image.open(file)
  draw = ImageDraw.Draw(im)
  draw.text((10,10), "{0:04d}".format(i), fill="#ff0")
  dst_file = "{dir}/{index:04d}.jpg".format(dir=dst_img_dir,index=i)
  im.save(dst_file)

処理後の画像はdstディレクトリに出力されている。動画に変換する前にここで処理内容を確認できる。

Screen Shot 2019-07-20 at 18.06.26.png

処理後の画像から動画を作る

最後に処理後の画像を動画に戻す。
ffmpegを使って、処理後の画像が納められているディレクトリ(dst)にある画像から動画ファイル(out.mp4)を作成する。
この際のフレームレートは、動画から画像を抽出した際に用いたフレームレートと一致させる必要がある。

!ffmpeg -framerate 1 -i "$dst_img_dir/%04d.jpg" "/content/gdrive/My Drive/videoexp/out.mp4"
15
20
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
15
20