Skip to content

Instantly share code, notes, and snippets.

@ricardodeazambuja
Last active October 7, 2020 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardodeazambuja/b79724bd0d091fed4c0d44143e9c3127 to your computer and use it in GitHub Desktop.
Save ricardodeazambuja/b79724bd0d091fed4c0d44143e9c3127 to your computer and use it in GitHub Desktop.
Saving images from webcam on Google Colab
# I have no idea who is the author of the code
# in this cell that saves an image from a webcam
# inside google colab.
# It comes from a notebook called "📸 Take a photo with your webcam"
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_HTML = """
<div class="video_container">
<video autoplay
width=%d height=%d></video>
<div style='position: absolute;top: 40px; left: 40px; font-size: 40px; color: green;'>Click to save!</div>
</div>
<script>
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
canvas.getContext('2d')
.drawImage(video, 0, 0, w, h)
video.srcObject.getVideoTracks()[0].stop()
video.replaceWith(canvas)
resolve(canvas.toDataURL('image/jpeg', %f))
}
})
</script>
"""
def take_photo(filename=None, quality=0.8, size=(800,600)):
handle = display(HTML(VIDEO_HTML % (size[0],size[1],quality)), display_id='videoHTML')
data = eval_js("data")
binary = b64decode(data.split(',')[1])
if filename:
f = io.BytesIO(binary)
Image.open(f).save(filename)
else:
f = io.BytesIO(binary)
return np.asarray(Image.open(f))
@rezguizinadev
Copy link

How to save the image under a given folder please ??

@ricardodeazambuja
Copy link
Author

ricardodeazambuja commented Oct 7, 2020

How to save the image under a given folder please ??

Hi, I updated it to give the option to save to a filename. I was not actually keeping this code, so I suggest checking this repo:
https://github.com/ricardodeazambuja/colab_utils

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment