简体   繁体   English

将 canvas 从客户端(浏览器)传递到服务器(nodejs)

[英]Pass canvas from client (browser) to server (nodejs)

I have a canvas in my browser that displays a feed from my webcam.我的浏览器中有一个 canvas,它显示来自我的网络摄像头的提要。 What I want to do, is send the canvas data to my nodejs server, manipulate it, and send it back.我想做的是将 canvas 数据发送到我的 nodejs 服务器,对其进行操作,然后将其发回。

I can do it sending the canvas data via socket.io like so:我可以通过 socket.io 发送 canvas 数据,如下所示:

socket.emit('canvas_data', canvas.toDataURL());

And then rebuilding it on the nodejs server:然后在 nodejs 服务器上重建它:

let img = new Image();
img.src = data;  // this is the canvas_data from the first step

const canvas = createCanvas(640,480);
const ctx = canvas.getContext('2d');
ctx.drawImage(img,0,0,640,480);

However this seems really wasteful as I'm taking an already rendered canvas, converting it to base64, sending it, and then rebuilding it on the other side.然而,这似乎真的很浪费,因为我正在使用已经渲染的 canvas,将其转换为 base64,发送它,然后在另一侧重建它。

The whole point of this is to use tfjs on the server side:这样做的重点是在服务器端使用 tfjs:

let converted = tfjs.browser.fromPixels(canvas);

If I just send the canvas from the first step:如果我只是从第一步发送 canvas:

socket.emit('canvas_data', canvas);

And then run tfjs:然后运行 tfjs:

let converted = tfjs.browser.fromPixels(data);

I get the following error:我收到以下错误:

Error: pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was object

Is there a more efficient way to accomplish this?有没有更有效的方法来实现这一点?

using toDataURL is always going to be slow as browser needs to由于浏览器需要,使用toDataURL总是会很慢
encode all data before sending it.在发送之前对所有数据进行编码。

your second example is better, just on the node side you need to create tensor from Buffer that you receive on socket (that would be fastest way), no need to use higher-level functions such as fromPixels你的第二个例子更好,只是在节点端你需要从你在套接字上收到的Buffer创建张量(这将是最快的方式),不需要使用更高级别的函数,比如fromPixels

take a look at https://github.com/vladmandic/anime/blob/main/sockets/anime.ts for client-side code andhttps://github.com/vladmandic/anime/blob/main/sockets/server.ts for server-side code查看https://github.com/vladmandic/anime/blob/main/sockets/anime.ts获取客户端代码和https://github.com/vladmandic/anime/blob/main/sockets/server .ts用于服务器端代码

note you also may need to account for channel-depth (does your model work with rgba or rgb ) and/or model specific any pre-processing normalization, that's handled in https://github.com/vladmandic/anime/blob/main/sockets/inference.ts note you also may need to account for channel-depth (does your model work with rgba or rgb ) and/or model specific any pre-processing normalization, that's handled in https://github.com/vladmandic/anime/blob/main /sockets/inference.ts

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

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