Capturing Images using Webcam in Jupyter Notebook

22 Views Asked by At

I am trying to use the webcam to capture images that I will use to predict the age and gender using neural networks.

from IPython.display import display, Javascript, HTML
import base64
# HTML template for capturing image from webcam
html_template = """
<!DOCTYPE html>
<html>
<head>
<title>Webcam Image Capture</title>
</head>
<body>

<div id="container">
    <video id="video" style="display:block; width:100%;" autoplay></video>
    <button id="captureButton">Capture</button>
</div>

<script>
    var video = document.querySelector("#video");
    var captureButton = document.querySelector("#captureButton");

    // Access the webcam
    navigator.mediaDevices.getUserMedia({ video: true })
    .then(function(stream) {
        video.srcObject = stream;
    })
    .catch(function(error) {
        console.log("Error accessing the webcam: " + error.message);
    });

    // Capture image
    captureButton.onclick = function() {
        var canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        var context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        var dataURL = canvas.toDataURL('image/jpeg');
        var imageData = dataURL.replace(/^data:image\/(png|jpeg);base64,/, "");
        // Send captured image data back to Python
        IPython.notebook.kernel.execute("image_data = '" + imageData + "'");
    };

</script>

</body>
</html>
"""

# Display the HTML template
display(HTML(html_template))

# Wait for image data to be captured
image_data = None
while image_data is None:
    pass

# Decode image data and save it to file
image_binary = base64.b64decode(image_data)
filename = 'my_photo.jpg'
with open(filename, 'wb') as f:
    f.write(image_binary)

# Display the captured image
display(Image(filename))

This is the code but I get this error in the console:

VM1495:24 Uncaught ReferenceError: IPython is not defined at captureButton.onclick (:24:9)

Ipython is usually installed automatically with jupyter and I actually imported from Ipython the following:

from IPython.display import display, Javascript
0

There are 0 best solutions below