如何将base64图像传递给tensorflow JS?

fruv7luv  于 2023-01-05  发布在  其他
关注(0)|答案(1)|浏览(135)
  • 我使用tensorflow JS来进行图像分类。
  • 我在浏览器indexDB中以数据格式(又名数据data:image/jpeg;base64,/9j/4A...)存储训练图像

当我训练的时候,我使用这个函数,它应该把我的数据IMG转换成Tensor。

const imageToTensor = (imageData: string) => {
    // convert base64 to Image for the fromPixels
    const img = new Image()
    img.src = imageData
    img.width = 224
    img.height = 224

    const imageFeatures = tf.tidy(function () {
        const imageAsTensor = tf.browser.fromPixels(img)
        imageAsTensor.print()
        return imageAsTensor
    })
    return imageFeatures
}

但我的imageAsTensor.print()显示的只是一堆000

Tensor
    [[[0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      ...,
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]],

     [[0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      ...,
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]],

     [[0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      ...,
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]],

     ...
     [[0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      ...,
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]],

     [[0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      ...,
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]],

     [[0, 0, 0],
      [0, 0, 0],
      [0, 0, 0],
      ...,
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]]]

看不出我做错了什么。我错过了等待还是什么?
谢谢你的帮助。

8yparm6h

8yparm6h1#

很难发现这个代码片段的问题,但是fromPixels方法需要一个HTML canvas元素或image元素作为输入,但是您传递的是一个尚未加载的image元素。您可以这样编辑:

const imageToTensor = (imageData: string) => {
    // convert base64 to Image for the fromPixels
    const img = new Image()
    img.src = imageData
    img.width = 224
    img.height = 224

    return new Promise((resolve) => {
        img.onload = () => {
            const imageFeatures = tf.tidy(function () {
                const imageAsTensor = tf.browser.fromPixels(img)
                imageAsTensor.print()
                return imageAsTensor
            })
            resolve(imageFeatures)
        }
    })
}

然后使用await关键字等待承诺解决,然后在模型中使用图像Tensor。

async function trainModel() {
    const imageData = 'data:image/jpeg;base64,/9j/4A...'
    const imageTensor = await imageToTensor(imageData)
    // Use the image tensor to train the model
}

相关问题