首页 > 解决方案 > 错误:传递给 tf.browser.fromPixels() 的像素必须是 HTMLImageElement

问题描述

尝试使用 TensorflowJS 进行预测。但是,在上面的输入图像中显示错误?我的图像是Uint8Array类型。如何传递 Uint8Array 类型来制作张量?


    
      async predict(imageData: any) {
    
        let img = tf.browser.fromPixels(imageData, 3).resizeBilinear([256, 256]) # problem showing here
        img = imageData.reshape([256, 256, 3])
        img = tf.cast(img, 'float32')
    
        const segmentation = this.model.predict(img) as any
    
        console.log('success')
    
      }
    
    
    loadImage(file: FileList) {
    
        this.fileToUpload = file.item(0);
        let reader = new FileReader();
        reader.readAsDataURL(this.fileToUpload);
    
        reader.onload = (event: any) => {
          this.imageUrl = reader.result
          this.predict(this.convertDataURIToBinary(this.imageUrl)); # passing Unit8Array image from here
        }
    
      }

知道如何克服它吗?谢谢你的建议。

更新

使用 '@ViewChild('ImageRef') ImageRef: ElementRef;' 解决了这个问题 . 最后,我将 Unit8Array 转换为 imageData,然后使用 putImageData 绘制到画布中。

但在另一部分面临问题。当我进行图像分割时,结果与我在 python 中所做的相反。任何想法?

在python中我做了->


    img_face = cv2.resize(frame,(256,256))
    img_face = cv2.cvtColor(img_face, cv2.COLOR_BGR2RGB)
    img_face = img_face / 255.0
    img_face = img_face.astype(np.float32)
    mask = model.predict(np.expand_dims(img_face , axis=0))[0]

而我当前的 js 部分已经在上面提到了 predict() func。

标签: javascriptangulartensortensorflow.jstensorflowjs-converter

解决方案


如果imageData是一个 UInt8Array,它可以很容易地转换为一个张量使用tf.tensor

tf.tensor(imageData)

此外,可以在创建张量时指定图像的宽度和高度

tf.tensor(imageData, [height, width, channels])

现在关于图像处理,在 python 中你正在做

img_face / 255.0

你在 js 中没有做同样的事情。你需要将 js 张量除以 255


推荐阅读