Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how play mp4 video in google colab

Tags:

I have a video.mp4 in content/video.mp4

if I wanted to play the video in google colab without downloading , ¿what code I should use to open a kind of video player in my jupyter notebook?

like image 343
molo32 Avatar asked Aug 06 '19 13:08

molo32


People also ask

How do I read uploaded files on Google Colab?

To start, log into your Google Account and go to Google Drive. Click on the New button on the left and select Colaboratory if it is installed (if not click on Connect more apps, search for Colaboratory and install it). From there, import Pandas as shown below (Colab has it installed already).


3 Answers

Here's the code

from IPython.display import HTML
from base64 import b64encode
mp4 = open('video.mp4','rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
HTML("""
<video width=400 controls>
      <source src="%s" type="video/mp4">
</video>
""" % data_url)

You can test it in a colab notebook here.

Update (Jun 2020)

To support a big vdo file, I write a library to upload to Google Drive and set it public. Then use the returned URL to display the video.

!pip install -U kora
from kora.drive import upload_public
url = upload_public('video.mp4')
# then display it
from IPython.display import HTML
HTML(f"""<video src={url} width=500 controls/>""")
like image 70
korakot Avatar answered Sep 18 '22 17:09

korakot


Currently, we need to compress the video file to play it in google colaboratory, if the format is not supported.

from IPython.display import HTML
from base64 import b64encode
import os

# Input video path
save_path = "/content/videos/result.mp4"

# Compressed video path
compressed_path = "/content/videos/result_compressed.mp4"

os.system(f"ffmpeg -i {save_path} -vcodec libx264 {compressed_path}")

# Show video
mp4 = open(compressed_path,'rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
HTML("""
<video width=400 controls>
      <source src="%s" type="video/mp4">
</video>
""" % data_url)

Reference: https://towardsdatascience.com/yolov3-pytorch-on-google-colab-c4a79eeecdea

like image 21
anilsathyan7 Avatar answered Sep 17 '22 17:09

anilsathyan7


Just input the mp4 video path to that function and you're good to go.

from IPython.display import HTML
from base64 import b64encode
 
def show_video(video_path, video_width = 600):
   
  video_file = open(video_path, "r+b").read()
 
  video_url = f"data:video/mp4;base64,{b64encode(video_file).decode()}"
  return HTML(f"""<video width={video_width} controls><source src="{video_url}"></video>""")
 
show_video(video_path)
like image 32
Mathias Godwin Avatar answered Sep 20 '22 17:09

Mathias Godwin