使用 NodeJS 访问网络摄像头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10808805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:46:49  来源:igfitidea点击:

Accessing WebCam with NodeJS

node.js

提问by Steve

Does anyone have any experience with trying to access a webcam through node? I can't seem to find any prior attempts at this.

有没有人有尝试通过节点访问网络摄像头的经验?我似乎找不到任何先前的尝试。

To expand a bit - I have a nodeJS server running, and I want to be able to access the webcam on the same box Node is running (so really, I'm using node more as a client implementation). Some things I wanted to do - get an image from the webcam, or, it'd be awesome if I could get a stream to the webcam that I pipe to another server and stream to other clients ;)

稍微扩展一下 - 我有一个 nodeJS 服务器正在运行,我希望能够在 Node 运行的同一台机器上访问网络摄像头(所以实际上,我更多地使用 node 作为客户端实现)。我想做的一些事情 - 从网络摄像头获取图像,或者,如果我可以将流传输到网络摄像头,然后通过管道传输到另一台服务器并传输到其他客户端,那就太棒了;)

Does anyone know how this can be done?

有谁知道如何做到这一点?

Thanks

谢谢

回答by Jesse Proulx

I don't think there's anything specific to Node.js when it comes to working with webcams, the concepts are generally the same no matter what language or server you're using. The hardware involved and the interfaces to that hardware is what should define your solution.

我认为在使用网络摄像头时,Node.js 没有任何特定的东西,无论您使用什么语言或服务器,概念通常都是相同的。所涉及的硬件和该硬件的接口应该定义您的解决方案。

The simplest case would be to serve individual snapshots that are periodically saved to disk by the webcam's included software, or you can make a system callthat invokes a local processor programto save a snapshot on demand. You can then serve a page using Node.js that periodically refreshes the latest snapshot.

最简单的情况是提供由网络摄像头附带的软件定期保存到磁盘的单个快照,或者您可以进行系统调用以调用本地进程程序来按需保存快照。然后,您可以使用 Node.js 提供一个页面,该页面会定期刷新最新快照。

Alternatively, you can interface directly with the webcam hardware using a controller tailored to the operating system (DirectShow, Windows Image Acquisition, IKPictureTaker, V4L2, etc.) and create a live video streamusing Node.js as the transport mechanism.

或者,您可以使用针对操作系统(DirectShowWindows Image AcquisitionIKPictureTakerV4L2等)定制的控制器直接与网络摄像头硬件连接,并使用 Node.js 作为传输机制创建实时视频流

If your webcam has a network interface and already offers a streaming server, you might want to look into a reverse proxy solution instead, using nginx or Apache for example. Here is a solutionwhere nginx is being used to proxy a webcam stream formatted by VLC.

如果您的网络摄像头有一个网络接口并且已经提供了一个流媒体服务器,那么您可能需要考虑使用反向代理解决方案,例如使用 nginx 或 Apache。这是使用nginx 代理由 VLC 格式化的网络摄像头流的解决方案

Here is a creative solution that captures a video stream by taking individual frames, encoding the image data, and using websockets to push the image data to a canvas element on a client page, using Node.js as the intermediate server.

这是一个创造性的解决方案,它通过获取单个帧、编码图像数据并使用 websockets 将图像数据推送到客户端页面上的画布元素来捕获视频流,使用 Node.js 作为中间服务器。

回答by Dmitry Weiner

It is also possible to use node.js library node-webcam

也可以使用 node.js 库node-webcam

Webcam.capture( "test_picture", function( err, data ) {} );

But I suppose it is simple wrapper of fswebcam.

但我想它是 fswebcam 的简单包装。

回答by Daniel T. Sobrosa

It's possible to use OpenCV with Node to access your camera... this article will give you a basic overview. https://community.risingstack.com/opencv-tutorial-computer-vision-with-node-js/

可以将 OpenCV 与 Node 结合使用来访问您的相机……本文将为您提供一个基本概述。 https://community.risingstack.com/opencv-tutorial-computer-vision-with-node-js/

Another way is to search by cameraon npm repository, you will find a lot of modules that deal with webcams.

另一种方法是在 npm 存储库上按摄像头搜索,您会发现很多处理网络摄像头的模块。

回答by Ryan Mann

I haven't dived into this yet, but you could possibly use Python to do it with OpenCV.

我还没有深入研究这个,但你可以使用 Python 和 OpenCV 来完成它。

Then you can use node-python to call python from Node.

然后就可以使用 node-python 从 Node 调用 python。

http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

https://www.npmjs.com/package/node-python

https://www.npmjs.com/package/node-python

Optionally if everything is running on Windows, you can use .Net and C# to talk to the camera and then use edge.js to make .Net calls.

或者,如果一切都在 Windows 上运行,您可以使用 .Net 和 C# 与相机对话,然后使用 edge.js 进行 .Net 调用。

Edge.Js supports linux now via Mono, you just need to be running a Linux distro that hos a mono package available, or build mono yourself.

Edge.Js 现在通过 Mono 支持 linux,你只需要运行一个带有可用 mono 包的 Linux 发行版,或者自己构建 mono。

回答by cancerbero

I'm working on my own library based on puppeteer (chrome headless browser) and so is 100% portable and works acceptably fine (40fps in my machine for video size 480x320) : https://www.npmjs.com/package/camera-capture. Has different ways of consuming the video stream and a command line API too. Very new project so feedback is very welcome.

我正在基于 puppeteer(chrome 无头浏览器)开发我自己的库,因此 100% 可移植并且工作正常(我的机器为 40fps,视频大小为 480x320):https: //www.npmjs.com/package/camera -捕获。也有使用视频流和命令行 API 的不同方式。非常新的项目,因此非常欢迎反馈。

回答by Aneh Thakur

accessing web in node application is very simple we just need to use html5 getUserMedia() method to do that and reaming part is very easy here is complete code please node i am using express framework:

在 node 应用程序中访问 web 非常简单,我们只需要使用 html5 getUserMedia() 方法来做到这一点,铰孔部分很容易这里是完整的代码请节点我使用快速框架:

Step 1.My layout.jade file in which i am accessing web cam

第 1 步。我在其中访问网络摄像头的 layout.jade 文件

extends layout
block content
  div(class="container" id="Cool" ng-app="mainApp" ng-controller="formController")
    h2.blue.red#header("property"="pValue") Capture your image from webcam
    div.row
     div.col-md-6
       video#video(autoplay='')
     div.col-md-6
       canvas#canvas(width='640', height='480')
    div
      button#snap Capture
      button#new New
      button(id="upload" ng-click="uploadImage()") Upload


  script(type="text/javascript").
   // Put event listeners into place
      window.addEventListener("DOMContentLoaded", function() {
      // Grab elements, create settings, etc.
      var canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      video = document.getElementById("video"),
      videoObj = { "video": true },
      errBack = function(error) {
      console.log("Video capture error: ", error.code);
      };
      // Put video listeners into place
      if(navigator.getUserMedia) { // Standard
      navigator.getUserMedia(videoObj, function(stream) {
      video.src = stream;
      video.play();
      }, errBack);
      } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
      navigator.webkitGetUserMedia(videoObj, function(stream){
      video.src = window.URL.createObjectURL(stream);
      video.play();
      }, errBack);
      } else if(navigator.mozGetUserMedia) { // WebKit-prefixed
      navigator.mozGetUserMedia(videoObj, function(stream){
      video.src = window.URL.createObjectURL(stream);
      video.play();
      }, errBack);
      }
      // Trigger photo take
      document.getElementById("snap").addEventListener("click", function() {
      context.drawImage(video, 0, 0, 640, 480);
      // Littel effects
      //$('#video').fadeOut('slow');
      $('#canvas').fadeIn('slow');
      //$('#snap').hide();
      //$('#new').show();
      // Allso show upload button
      //$('#upload').show();
      });
      // Capture New Photo
      document.getElementById("new").addEventListener("click", function() {
      //$('#video').fadeIn('slow');
      //$('#canvas').fadeOut('slow');
      //$('#snap').show();
      //$('#new').hide();
      });
      // Upload image to sever
      document.getElementById("upload").addEventListener("click", function(){
      var dataUrl = canvas.toDataURL();
       console.log(dataUrl);

      });
      }, false);   
   var mainApp = angular.module("mainApp", []);
   mainApp.controller("formController", function($scope, $http) {
       $scope.uploadImage = function () {
         var request = $http({
            method: "post",
            url:  "/captureImage",
            data: {
               base64: document.getElementById("canvas").toDataURL()
            },
            headers: { 'Content-Type': 'application/json' }
          });
        request.success(function (data) {
          console.log(data);
        });
        request.error(function(serverResponse, status, headers, config) {
           alert("failure");
        });
      };
   });

Step 2.my routes file in which i hand or save my uploaded image

步骤 2.我的路线文件,我将上传的图片保存在其中

router.get('/captureImage', function(req, res, next) {
    res.render('captureImage', { title: 'Capture Image and upload' });
});

router.post('/captureImage', function(req, res, next) {
    //console.log("FormData "+ req.body.base64);
    var base64Data = req.body.base64.replace(/^data:image\/png;base64,/, "");
    fs.writeFile("uploads/out.png", base64Data, 'base64', function(err) {
        if(err){
            console.log(err);
            }else{
            res.send(JSON.stringify({'status': 1, 'msg': 'Image Uploaded'}));
        }
    });
});

For complete tutorial please follow link Accessing WebCam with NodeJS and save click image - TrinityTuts

如需完整教程,请点击链接使用 NodeJS 访问网络摄像头并保存点击图片 - TrinityTuts