有没有一种方法可以使用fromPixels方法从File对象创建张量?

时间:2020-07-17 06:29:49

标签: reactjs tensorflow-serving tensorflow.js

我目前正在使用进行图像分类的前端上的React.js创建一个Web应用程序。我遇到的一个问题是能够使用Tensorflow.js的fromPixels方法制作图像张量。我收到的错误是:

未处理的拒绝(错误):传递给tf.browser.fromPixels()的像素必须是HTMLVideoElement,HTMLImageElement,HTMLCanvasElement,浏览器中的ImageData或OffscreenCanvas,webworker中的ImageData或{data:Uint32Array,width:number,height :number},但为String

另外,这是我的代码:

async onSubmit(e){
e.preventDefault()

const model = await tf.loadLayersModel('http://localhost:81/model/model.json')

const reader = new FileReader()


reader.readAsDataURL(this.state.image)

 
const tensor =  tf.browser.fromPixels(reader.result)
      .resizeNearestNeighbor([224,224])
      .toFloat()
      .expandDims()

const predictions = await model.predict(tensor).data()

console.log(predictions)



const formdata = new FormData()
formdata.append('caption',this.state.caption)//key-value pair
formdata.append('description',this.state.description)
formdata.append('date', this.state.date)
formdata.append('image',this.state.image)


//creating  a formdata object

console.log('Image uploaded !')

axios.post('http://localhost:3002/images',formdata)
  .then(res=>console.log(res.data))


//window.location = '/results'
//this will go to the 'results' page--where the image is displayed

}

另外,对于上下文,这是我的渲染功能:

render(){
return(
  
  <div>
    <form onSubmit = {this.onSubmit}>
      <div className="form-group">
        <label>Caption:</label>
        <input type="text"
            required
            className="form-control"
            value={this.state.caption}
            onChange={this.onChangeCaption}
            />

      </div>

      .....{//removed some code not relevant to the question here}

      <div className="form-group">
        <label>Choose a File</label>
        <input type="file" 
          className="form-control"
          onChange={this.onChangeImage}
          />

      </div>

      <div className="form-group">{//submit button}
        <input type="submit" value = "Upload Data" className = "btn btn-primary"/>
      </div>



      </form>
   </div>

  
    )
  }

基本上,在提交表单时以及要向我的REST API发出发布请求时,会调用onSubmit函数。

我不知道如何预处理存储在this.state.image中的文件对象。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用FileReader创建一个img元素并从那里加载它:

const image = document.createElement("img");

reader.onload = async (event) => {
  image.src = event.target.result
  document.body.append(image);

  image.onload = async () => {
    tf.browser.fromPixels(image);
  }
}