简体   繁体   English

访问摄像头视频流的像素(JS / WebRTC / MediaStreamTrack)

[英]Access pixels of a webcam's video stream (JS/WebRTC/MediaStreamTrack)

For a scientific application, I need to do live processing of the video stream received from the web cam in JavaScript. 对于科学应用程序,我需要对从网络摄像头接收的视频流进行实时处理。

WebRTC makes it simple to display the live stream on a web site, and using a <canvas> also allows to take and process screenshots . WebRTC使在网站上显示实时流变得很简单,并且使用<canvas>还可以获取和处理屏幕截图

I need to track brightness of the video image. 我需要跟踪视频图像的亮度。 Therefore, what I need is a stream of a few pixels (their RGB values) over time. 因此,我需要的是随时间流过几个像素(它们的RGB值)的流。 It seems very inefficient to copy the <video> to a <canvas> 30 times per second just to have a still image and analyse a fews pixels... 每秒将<video>复制到<canvas> 30次只是为了获得静止图像并分析几个像素,似乎效率很低。

Is there any way to access the video content of a MediaStreamTrack more directly? 有什么方法可以更直接地访问MediaStreamTrack的视频内容?

Is there any way to access the video content of a MediaStreamTrack more directly? 有什么方法可以更直接地访问MediaStreamTrack的视频内容?

Not real-time, no. 不是实时的,不。 The W3C has discussed adding such an API in workers, but none exists today. W3C已经讨论了在工作程序中添加这样的API,但是今天还不存在。

The MediaRecorder API comes close: it can give you blobs of data at some millisecond interval (see start(timeslice) ), but it's not real-time. MediaRecorder API接近了:它可以在几毫秒的间隔内为您提供大量的数据(请参阅start(timeslice) ),但这不是实时的。

It seems very inefficient... 看来效率很低...

Modern browsers have background threads to do heavy lifting like downscaling, so I'd caution against premature optimization. 现代的浏览器具有后台线程来执行繁重的工作,例如缩小规模,因此,请注意不要过早优化。 Things generally only slow down when bits are exposed en masse to main thread JavaScript. 通常,只有将比特全部暴露给主线程JavaScript时,事情才会放慢速度。 Therefore I'd worry less about your camera resolution than the size of your canvas. 因此,我担心的不是您的相机分辨率,而是画布的大小。

If you only need a few pixels for brightness, make your canvas real tiny. 如果您只需要几个像素的亮度,则使画布很小。 The overhead should be low. 开销应该很低。 Eg : 例如

video.srcObject = await navigator.mediaDevices.getUserMedia({video: true});
await new Promise(r => video.onloadedmetadata = r);
const ctx = canvas.getContext('2d');
requestAnimationFrame(function loop() {
  ctx.drawImage(video, 0, 0, 16, 12);
  requestAnimationFrame(loop);
});
<canvas id="canvas" width="16" height="12"></canvas>

If overhead is still a concern, I'd reduce the frame rate. 如果仍然需要开销,我会降低帧速率。

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

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