import cv2
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
!pip install youtube_dl
import youtube_dl
Requirement already satisfied: youtube_dl in /usr/local/lib/python3.6/dist-packages (2019.8.13)
from IPython.display import HTML
from IPython.display import IFrame
from IPython.display import display
print("IPython.display.HTML() による youtube 動画の表示")
display(HTML(r'<iframe width="560" height="315" src="https://www.youtube.com/embed/GrkyTO9uu-c" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'))
print("IPython.display.IFrame() による youtube 動画の表示")
display(IFrame(src="https://www.youtube.com/embed/GrkyTO9uu-c",width=560,height=315))
IPython.display.HTML() による youtube 動画の表示
IPython.display.IFrame() による youtube 動画の表示
jupyter notebook は各セルの一番下のコードの実行結果のみを表示する仕様になっているが,IPython.display.display() を使えば,最後以外の文の実行結果も表示することができる.上のプログラムでは, IFrame() の方は最後の文なので,実際には display() で囲む必要はない.
(* ) HTML()による動画表示は最近の python では推奨されていないらしく,python のバージョンによっては,1回目の実行時のみ,"Consider using IPython.display.IFrame instead"という警告がでる.
下のプログラムは Youtube にアップしてある動画を 640x360 の解像度でダウンロードし,"tmpv.mp4" という名前で保存する.
# 動画を一時的に tmpv.mp4という名前で作業フォルダに保存
# Youtube動画には著作権がある.くれぐれも悪用しないように
url = 'https://youtu.be/GrkyTO9uu-c'
vname = 'tmpv.mp4'
ydl = youtube_dl.YoutubeDL({'outtmpl': vname,'format':'18'}) # 640x360 mp4
# ydl = youtube_dl.YoutubeDL({'outtmpl': 'test.%(ext)s','format':'133'}) # 426x230 mp4
# ydl = youtube_dl.YoutubeDL({'outtmpl': 'test.%(ext)s','format':'135'}) # 854x480 mp4
# ydl = youtube_dl.YoutubeDL({'outtmpl': 'test.%(ext)s','format':'136'}) # 1280x720 mp4
# ydl = youtube_dl.YoutubeDL({'outtmpl': 'test.%(ext)s','format':'137'}) # 1920x1080 mp4
# meta = ydl.extract_info(url, download=False)
# print(meta['format'])with ydl:
result = ydl.extract_info(url,download=True)
[youtube] GrkyTO9uu-c: Downloading webpage [youtube] GrkyTO9uu-c: Downloading video info webpage [youtube] GrkyTO9uu-c: Downloading MPD manifest [download] tmpv.mp4 has already been downloaded [download] 100% of 486.06KiB
def makeAnimation(frames):
plt.figure(figsize=(frames[0].shape[1]/72.0, frames[0].shape[0]/72.0), dpi=72)
patch = plt.imshow(frames[0])
plt.axis('off')
def animate(i):
patch.set_data(frames[i])
anim = FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=1000/30.0)
display(HTML(anim.to_jshtml()))
movie = "tmpv.mp4"
cap = cv2.VideoCapture(movie)
# 最初の30フレームを取り出す
ret, frame = cap.read()
imgs = [frame] # 最初のフレーム
for i in range(29):
ret, frame = cap.read()
imgs.append(frame)
makeAnimation(frames=imgs)