In [1]:
%matplotlib inline
%pylab inline 

from __future__ import unicode_literals
from IPython.display import YouTubeVideo, clear_output
import youtube_dl

import cv2
import os


Populating the interactive namespace from numpy and matplotlib

In [8]:
# Video filename
video_url = "https://www.youtube.com/watch?v=Cn0imlPptok"

video_id = video_url.split('=')[-1]
video_fn = video_id + '.mp4'
YouTubeVideo(video_id)
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})
cwd = os.getcwd()

with ydl:
    ydl.download([video_url])

vid = cv2.VideoCapture(video_fn)

try:
    frames = []
    while(True):
        # Capture frame-by-frame
        ret, frame = vid.read()
        if not ret:
            vid.release()
            print "Released Video Resource"
            break

        # Convert the image from OpenCV BGR format to matplotlib RGB format
        # to display the image
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frames.append(frame.astype(np.uint8))
      
except KeyboardInterrupt:
    vid.release()
    print "Released Video Resource - interrupt"

video = np.array(frames)
print video.shape, video.dtype
N, h, w, chan = video.shape

In [21]:
depth_levels = 256

inspect_frames = False
to_inspect = [170, 200,300,400,500,800,1000, 1100]

if inspect_frames:
    for i in to_inspect:
        axis('off')
        title("Inspect frames - Frame %d" % i)
        imshow(video[i])
        show()
else:
    min_frame = 170
    max_frame = 1100

    frames = np.linspace(min_frame, max_frame, num=depth_levels, dtype=np.int32)

    dvideo = video[frames].astype(np.uint8)
    print dvideo.shape, dvideo.dtype
    np.save(video_fn[:-4] + "_" + str(depth_levels) + ".npy", dvideo)


(256, 720, 1280, 3) uint8