Created
October 20, 2023 18:24
-
-
Save ajangrahmat/bab594fcd53f802b4926bf72fc5376bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from IPython.display import display, Javascript | |
from google.colab.output import eval_js | |
from base64 import b64decode | |
def take_photo(filename='photo.jpg', quality=0.8): | |
js = Javascript(''' | |
async function takePhoto(quality) { | |
const div = document.createElement('div'); | |
const capture = document.createElement('button'); | |
capture.textContent = 'Capture'; | |
div.appendChild(capture); | |
const video = document.createElement('video'); | |
video.style.display = 'block'; | |
const stream = await navigator.mediaDevices.getUserMedia({video: true}); | |
document.body.appendChild(div); | |
div.appendChild(video); | |
video.srcObject = stream; | |
await video.play(); | |
google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true); | |
await new Promise((resolve) => capture.onclick = resolve); | |
const canvas = document.createElement('canvas'); | |
canvas.width = video.videoWidth; | |
canvas.height = video.videoHeight; | |
canvas.getContext('2d').drawImage(video, 0, 0); | |
stream.getVideoTracks()[0].stop(); | |
div.remove(); | |
return canvas.toDataURL('image/jpeg', quality); | |
} | |
''') | |
display(js) | |
data = eval_js('takePhoto({})'.format(quality)) | |
binary = b64decode(data.split(',')[1]) | |
with open(filename, 'wb') as f: | |
f.write(binary) | |
return filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment