5
5

More than 3 years have passed since last update.

Google Colab のインラインに動画を表示する方法

Last updated at Posted at 2020-08-12

1.はじめに

 Google Colabのインラインに動画を表示するコードを備忘録として残します。

2.やり方

 imageio で動画を読み込みフレームにばらします。そして、おなじみの matplotlibanimetion を使ってアニメーション形式にして、 HTML5へ送るとインラインに動画を表示できます。

import imageio
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML

# 動画をアニメに変換
def video_anime(video):
    video = imageio.mimread(video)   # フレームにばらす
    fig = plt.figure(figsize=(3,3))  # 表示サイズ指定

    mov = []
    for i in range(len(video)):  # フレームを1枚づつmovにアペンド
        img = plt.imshow(video[i], animated=True)
        plt.axis('off')
        mov.append([img])

    # アニメーション作成        
    anime = animation.ArtistAnimation(fig, mov, interval=50, repeat_delay=1000)
    plt.close()
    return anime

# HTML5でアニメをインラインに動画表示 
HTML(video_anime('./sample/00.mp4').to_html5_video())   

スクリーンショット 2020-08-15 11.04.11.png

<追記 2021.5.29>

 もっと簡単な方法があったので、サンプルコードを追記します。

# mp4動画の再生
from IPython.display import HTML
from base64 import b64encode

mp4 = open('./sample/00.mp4', 'rb').read()
data_url = 'data:video/mp4;base64,' + b64encode(mp4).decode()
HTML(f"""
<video width="100%" height="100%" controls>
      <source src="{data_url}" type="video/mp4">
</video>""")

 こっちの方がシンプルなのでおすすめです。

5
5
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
5
5