我想使用webworker来处理一些任务。
主线程:首先,我使用tf.loadFrozenModel()来加载前列车模型。其次,我使用model.predict()来预测图像(大小:512 * 512 * 4)。当我使用const data = await tf.toPixels(image)
来获取图像时像素,需要花费大量时间,导致UI操作导致卡纸。所以我想用webworker来处理这个问题。
const y=tf.tidy(() => {
......
var output=model.predict(
{[INPUT_NODE_NAME]: imageConcat}, OUTPUT_NODE_NAME);
......
return output
})
webworker.postMessage({headpackage:y});//y is the predicted image
在webworker中:
importScripts('https://cdn.jsdelivr.net/npm/[email protected]/setImmediate.min.js')
importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]')
var dataMessage;
self.addEventListener('message', function (e) {
dataMessage = e.data;
a();
}, false);
async function a() {
const data = await tf.toPixels(dataMessage["headpackage"]);
//Change the value of image data
var image={
data:new Uint8Array(data),
width:512,
height:512
};
tfoutputtexture.image=image;
tfoutputtexture.flipY=true;
tfoutputtexture.needsUpdate = true;
}
您可以发送一个类型化的数组,而不是将张量对象发送给webworker。
从版本15开始,类型化数组与使用tensor.array
的张量具有相同的形状。
webworker.postMessage({headpackage:await y.array()})
// Webworker
tf.toPixels(tf.tensor(dataMessage["headpackage"]));
如果您使用的是15之前的版本,则需要传入类型化数组及其形状。
webworker.postMessage({headpackage:y.dataSync(), shape: y.shape})
// Webworker
tf.toPixels(tf.tensor(dataMessage["headpackage"], dataMessage["shape"]));