在Jupyter Notebook中使用摄像头捕捉图像
我正在尝试使用摄像头捕捉图像,这些图像将用于通过神经网络预测年龄和性别。
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))
这是我的代码,但在控制台中出现了这个错误:
VM1495:24 未捕获的引用错误:IPython未定义 在captureButton.onclick (:24:9)
通常,Ipython会和jupyter一起自动安装,而我实际上是从Ipython导入了以下内容:
from IPython.display import display, Javascript
0 个回答
暂无回答