首页 > 解决方案 > TensorFlowJS 需要 HTML 吗?或者我可以从我的电脑上传图片和视频吗?

问题描述

我正在尝试创建一个在 Discord.js 上运行的对象分类器不和谐机器人,一切都进行得相对顺利,但我遇到了这个错误:

pixels passed to tf.browser.frompixels() cannot be null

据我了解,这是因为我使用的是计算机中的图像,而不是带有“ <img>”标签的 HTML 图像。

所以我想知道我是不是错了,有办法解决这个问题还是这不可能?

注意:我使用 COCO-SSD 作为预训练模型

标签: javascripthtmlnode.jsdiscord.js

解决方案


您可以使用经过训练的模型从计算机中的视频或图像中检测对象。我已经完成了一个完整的项目,你可以在这里查看

或按照以下步骤操作。
1-加载模型

const coco = require('@tensorflow-models/coco-ssd')

const loadModel =async()=>{
    try{
        const model = await coco.load()
        return model
    }catch(err){
        console.log("there was an error loading the model trying re-loading attempt...")
        return 0;
    }
}

module.exports = loadModel

2-读取图像并转动并转换它,以便模型可以读取它。

const fs = require('fs')
const tf = require('@tensorflow/tfjs-node')

ImageName = '../VidUploads/imageUp-1589491328827.jpg'

const readImage = (path)=>{
    const buffer = fs.readFileSync(path)
    try { 
      const pixels =tf.node.decodeImage(new Uint8Array(buffer),3)
      console.log(`image shape ${pixels.shape}`)
      return pixels 
    }catch(err){
      console.log(`something went wrong while converting the image to tensor`)
      return -1 
    }
   
   
}

3-使用模型

const imagePrediction =async(model , image)=>{

           return ( await model.detect(image))    
}

注意:imagePrediction步骤 2 中的模型和步骤 1 中的图像作为输入。


推荐阅读