简体   繁体   English

Javascript - imageCapture.takePhoto() function 拍照

[英]Javascript - imageCapture.takePhoto() function to take pictures

I am building an web application for my experiment purpose.我正在为我的实验目的构建一个 web 应用程序。 The aim here is to capture ~15-20 frames per second from the webcam and send it to the server.这里的目标是每秒从网络摄像头捕获约 15-20 帧并将其发送到服务器。 Once the frame is captured, it is converted to base64 and added to an array.捕获帧后,将其转换为 base64 并添加到数组中。 After certain time, it is sent back to the server.一定时间后,它被发送回服务器。 Currently I am using imageCapture.takePhoto() to achieve this functionality.目前我正在使用imageCapture.takePhoto()来实现这个功能。 I get blob as a result which is then changed to base64.结果我得到了blob,然后将其更改为base64。 The application runs for ~5 seconds and during this time, frames are captured and sent to the server.应用程序运行约 5 秒,在此期间,捕获帧并将其发送到服务器。

What are the more efficient ways to capture the frames through webcam to achieve this?通过网络摄像头捕获帧以实现这一目标的更有效方法是什么?

You can capture still images directly from the <video> element used to preview the stream from .getUserMedia() .您可以直接从用于从.getUserMedia()预览 stream 的<video>元素捕获静止图像。 You set up that preview, of course, by doing this sort of thing (pseudocode).当然,您可以通过执行此类操作(伪代码)来设置该预览。

const stream = await navigator.getUserMedia(options)
const videoElement = document.querySelector('video#whateverId')
videoElement.srcObject = stream
videoElement.play()

Next, make yourself a canvas object and a context for it.接下来,让自己成为 canvas object 及其上下文。 It doesn't have to be visible.它不一定是可见的。

const scratchCanvas = document.createElement('canvas')
scratchCanvas.width = video.videoWidth
scratchCanvas.height = video.videoHeight
const scratchContext = scratchCanvas.getContext('2d')

Now you can make yourself a function like this.现在你可以像这样让自己成为 function。

function stillCapture(video, canvas, context) {
    context.drawImage( video, 0, 0, video.videoWidth, video.videoHeight)  
    canvas.toBlob(
           function (jpegBlob) {
               /* do something useful with the Blob containing jpeg */
           }, 'image/jpeg')
}

A Blob containing a jpeg version of a still capture shows up in the callback.包含 jpeg 版本的静态捕获的 Blob 显示在回调中。 Do with it whatever you need to do.用它做任何你需要做的事情。

Then, invoke that function every so often.然后,每隔一段时间调用一次 function。 For example, to get approximately 15fps, do this.例如,要获得大约 15fps,请执行此操作。

const howOften = 1000.0 / 15.0
setInterval (stillCapture, howOften, videoElement, scratchCanvas, scratchContext)

All this saves you the extra work of using .takePhoto() .所有这些都为您节省了使用.takePhoto()的额外工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM