如何使用OpenCV为桌面和Web构建简单的Webcam应用程序(二)

在大流行期间,由于 交距离遥远,对相机应用程序的需求激增。因此,我收集了一些用不同编程语言实现的基本OpenCV 络摄像头示例代码,并构建了一些用于远程 络摄像头访问的简单Web应用程序。希望这对开始构建 络摄像头应用程序的人有所帮助。

Dynamic Web TWAIN正式版

从任何Web浏览器访问远程 络摄像头

要实现远程 络摄像头访问,我只需要创建一个带有图像元素的简单HTML页面并启动一个简单的HTTP服务器,即可通过HTTP GET请求连续发送 络摄像头帧。为了使代码尽可能简单,我只使用了四种编程语言的内置HTTP API和OpenCV视频捕获API。

Node.js

创建一个简单的HTML页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html ><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title>Webcam</title></head><body>    <img id="image"/>    <script type="text/javascript">        var image = document.getElementById('image');        function refresh() {            image.src = "/image + new Date().getTime();            image.onload= function(){                setTimeout(refresh, 30);            }        }         refresh();    </script></body></html>

使用setTimeout()从Web服务器连续获取新图像并刷新图像元素。

在服务器端,使用HTTP模块创建一个简单的Web服务器:

const http = require('http');var server = http.createServer(function (req, res) {    if (req.url === '/' || req.url === '/index.htm') {         res.writeHead(200, { 'Content-Type': 'text/html' });        res.write(html);        res.end();    }    else if (req.url.startsWith("/image")) {         res.writeHead(200, { 'Content-Type': 'image/jpeg' });        res.write(img);        res.end();    }    else        res.end('Invalid Request!');});server.listen(2020);

分析请求URL,然后发送相应的响应。同时,创建一个计时器以捕获 络摄像头帧并将其编码为JPEG格式:

var img = null;function capture() {    var frame = wCap.read()    if (frame.empty) {        wCap.reset();        frame = wCap.read();    }    img = cv.imencode('.jpg', frame);    setTimeout(capture, 30);}capture();

要通过双击打开HTML文件,请将相对图像路径更改为绝对图像路径:

image.src = "http://localhost:2020/image + new Date().getTime();

C#

受本杰明·萨默顿(Benjamin Summerton)的要旨启发,我创建了HTTP服务器,如下所示:

using System;using System.IO;using System.Text;using System.Net;using System.Threading.Tasks;using OpenCvSharp;namespace Web{    class Program    {        public static HttpListener listener;        public static string url = "http://localhost:2020/";        public static string pageData =            "" +            "" +            "" +            "HttpListener Example" +            "" +            "" +            """+            ""