Information at sight.

Use camera in Google Colab to take images

Reading time: 1 min
from IPython.display import HTML, Audio
from google.colab.output import eval_js
from base64 import b64decode
import numpy as np
import io
from PIL import Image

<video autoplay
 width=%d height=%d style='cursor: pointer;'></video>

var video = document.querySelector('video')

navigator.mediaDevices.getUserMedia({ video: true })
  .then(stream=> video.srcObject = stream)
var data = new Promise(resolve=>{
  video.onclick = ()=>{
    var canvas = document.createElement('canvas')
    var [w,h] =[video.offsetWidth, video.offsetHeight]
    canvas.width = w
    canvas.height = h
          .drawImage(video, 0, 0, w, h)
    resolve(canvas.toDataURL('image/jpeg', %f))
def take_photo(filename='photo.jpg', quality=0.8, size=(800,600)):
  display(HTML(VIDEO_HTML % (size[0],size[1],quality)))
  data = eval_js("data")
  binary = b64decode(data.split(',')[1])
  f = io.BytesIO(binary)
  return np.asarray(

img = take_photo()
im = Image.fromarray(img)"test.jpg")

You can view a whole project using this code to access the camera from the link below:

Get real time updates directly on you device, subscribe now.

%d bloggers like this: