我尝试使用tensorflowjs和一个已经构建好的模型,起初我遇到了blazeface的问题,因为它无法在仅显示面部的照片上找到面部,所以我尝试使用mobilenet,结果同样毫无意义。因此我非常确定问题出在我发送的图像格式上。
这是我的代码:
module.exports = { blazeface: require('@tensorflow-models/blazeface'), mobilenet: require('@tensorflow-models/mobilenet'), tf: require("@tensorflow/tfjs-node"), fs: require("fs"), sizeOf: require("image-size"), async structureData(imageLink) { let data = this.fs.readFileSync(imageLink);//返回一个缓冲区 const dimension = await this.sizeOf(imageLink); const tensorflowImage = { data: data, width: dimension.width, height: dimension.height }; console.log(tensorflowImage) return tensorflowImage; }, async detectFace(imageLink) { let image = await this.structureData(imageLink); const model = await this./*blazeface*/mobilenet.load(); const returnTensors = false; const predictions = await model.classify(image); console.log(predictions); }}
这段代码没有报错,但结果是这样的=>
[ { className: 'theater curtain, theatre curtain', probability: 0.03815646469593048 }, { className: 'web site, website, internet site, site', probability: 0.0255243219435215 }, { className: 'matchstick', probability: 0.02520526386797428 }]
无论使用哪张照片(这里是一张白色背景下的香蕉),所以我非常确定我需要重建structureData函数,但我不知道该怎么做…我也尝试过使用uint32array
async structureData(imageLink) { let data = this.fs.readFileSync(imageLink); data = new Uint32Array(data); const dimension = await this.sizeOf(imageLink); const tensorflowImage = { data: data, width: dimension.width, height: dimension.height }; console.log(tensorflowImage) return tensorflowImage; },
但我得到了这个错误。
Error: pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was Object
请记住,我使用的是Node.js,所以我认为我不能(或不确定我能否)使用HTMLImageElement
非常感谢你:)
回答:
通过使用张量、视频或图像元素作为模型的参数,它将能够进行分类。
let data = this.fs.readFileSync(imageLink);tensor = tf.node.decodeImage(data, 3)await model.classify(tensor)