Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To initiate the web camera in Google Colab, we can follow these steps:

  1. Run the following code snippet:
from google.colab import output
from base64 import b64decode
from IPython.display import HTML

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();

      // Resize the output to fit the video element.
      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);

      // Wait for Capture to be clicked.
      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)

  # Get the photo
  data = eval_js('takePhoto({})'.format(quality))
  binary = b64decode(data.split(',')[1])

  # Save the photo
  with open(filename, 'wb') as f:
    f.write(binary)
  return filename

# Take a photo
take_photo()
  1. Once the code is executed, we will see a button "Capture" and a video stream from the webcam.

  2. Click on the "Capture" button to take a photo.

  3. The photo will be saved as "photo.jpg" in the current directory.

  4. We can then use the saved image file for any further processing.