将Base64图像转换为张量。

3
我将base64字符串作为图像发送到node express服务器,以使用tensorflow进行物体检测。如何在Node.js中将base64图像更改为cocossd模型的张量以进行物体检测。
2个回答

6

服务器端的NodeJs

可以将Base64字符串转换为二进制,然后使用tf.node读取为张量。

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

如果没有发送其他属性或值,最好在 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)

第一种选项是同步的。对于大图像,它可能会冻结主线程。为了缓解这个问题,可以在 Web Worker 中执行此操作。

另一个选项是创建一个图像元素,并将其 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)
   })()

在服务器端的node.js中,tf.tensor(b, shape)中的shape参数应该是什么值? - Jayaprakash
第二个解决方案中,我遇到了错误:“model.execute(dict)”中提供的“dict['image_tensor']”形状必须为[-1,-1,-1,3],但实际上是[1,629051]。@edkeveked,请问我应该如何给张量指定形状? - Jayaprakash
形状应为[高度,宽度,通道]。您需要知道图像的宽度和高度。您可以添加一个批处理维度(最左侧位置),这将使形状变为[b,高度,宽度,通道]。当您使用tf.fromPixels时,它会直接返回3d或4d张量,与之不同。 - edkeveked
1
{ base64: '/9j/4AAQSkZJRgABAQAASABIAA........', width: 722, pictureOrientation: 1, deviceOrientation: 1, height: 1280 } 这是我的base64图像分辨率。我在服务器上使用的代码是: let buff = Buffer.from(data.photo.base64,'base64') let tensor = tf.tensor(buff,[data.photo.height,data.photo.width,3]) 但是我在获取张量时遇到了错误,错误信息为根据提供的形状[1280,722,3],张量应该有2772480个值,但只有610963个 - Jayaprakash
@Jayaprakash,你找到解决方案了吗? - mbauer

0
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接