有这个 javascript 代码可以在 colab 上运行您的本地系统摄像头,该 .ipynb 文件在 colab 上运行良好并且摄像头打开但是当我尝试将其转换为 .py 并在我的本地系统上运行它时会弹出此错误,我的系统中安装了其他 google-colab 库。
用于运行相机的js代码:
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();
// 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)
data = eval_js('takePhoto({})'.format(quality))
binary = b64decode(data.split(',')[1])
with open(filename, 'wb') as f:
f.write(binary)
return filename
错误信息:
Traceback (most recent call last):
File "repnet_task2.py", line 969, in <module>
record_video(INTERVAL_IN_MS, int(RECORDING_TIME_IN_SECONDS*1000/INTERVAL_IN_MS))
File "repnet_task2.py", line 752, in record_video
eval_js('recordVideo({},{},{})'.format(interval_in_ms, num_frames, quality))
File "/home/hp/Downloads/env/lib/python3.8/site-packages/google/colab/output/_js.py", line 35, in eval_js
kernel = _ipython.get_kernel()
File "/home/hp/Downloads/env/lib/python3.8/site-packages/google/colab/_ipython.py", line 28, in get_kernel
return get_ipython().kernel
AttributeError: 'NoneType' object has no attribute 'kernel'