将base64图像转换为张量

convert base64 image to tensor

我将图像作为 base64 字符串发送到 Node Express 服务器,以使用 TensorFlow 分析对象检测。如何在节点js中使用cocossd模型将base64图像更改为对象检测的张量

服务器端NodeJs

base64 字符串可以转换为二进制,然后使用 tf.node

读取为张量
 const b = Buffer.from(base64str, 'base64')
    // get the tensor
 const t = tf.node.decodeImage(b)

如果其他 properties/values 没有随请求一起发送,最好直接在 post 请求或 websocket 中以二进制形式发送图像。在那种情况下,不需要从 base64 服务器端重做转换

浏览器端

const b = atob(base64str)
let byteNumbers = new Array(b.length);
for (let i = 0; i < b.length; i++) {
    byteNumbers[i] = b.charCodeAt(i);
}
let tensor = tf.tensor(byteNumbers)

第一个选项是同步的。对于大图像,它可能会冻结主线程。为了减轻这种情况,可以在网络工作者中完成此操作。

另一种选择是创建一个图像元素并将其 href 属性设置为 base64str,然后使用 tf.browser.fromPixels

function load(url){
  return new Promise((resolve, reject) => {
    const im = new Image()
        im.crossOrigin = 'anonymous'
        im.src = 'url'
        im.onload = () => {
          resolve(im)
        }
   })
}

// use the load function inside an async function   

(async() => {
     const image = await load(url)
     let tensor = await tf.browser.fromPixels(image)
   })()
const readImage = path => {
 //reads the entire contents of a file.
 //readFileSync() is synchronous and blocks execution until finished.
 const imageBuffer = fs.readFileSync(path);
 //Given the encoded bytes of an image,
 //it returns a 3D or 4D tensor of the decoded image. Supports BMP, GIF, JPEG and PNG formats.
 const tfimage = tfnode.node.decodeImage(imageBuffer);
 return tfimage;
}