tf.browser.fromPixels从img元素返回全零

时间:2019-07-17 16:39:48

标签: javascript html tensorflow.js

我正在使用tensorflowjs进行一些前端图像分类。我正在尝试使用tf.browser.fromPixels将img元素转换为张量。但是,我得到了形状为[160, 160, 3]的所有零。我正在使用FileReader api通过<input type="file">元素从文件系统中读取图像。这里是一些代码:

function getFiles(event) {
  const files = event.target.files;
  let tempStore = [];
  for (let i = 0; i < files.length; ++i) {
    tempStore.push(files[i]);
  }
  return tempStore;
}
const imageElement = document.getElementById("upload");
  imageElement.addEventListener("change", event => {
    const files = getFiles(event);
    Promise.all(files.map(loadImg)).then(d => {
      console.log("All done !!!", d);
    });
  });
const loadImg = imgFile => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let imgEl = document.createElement("img");
    reader.onload = async e => {
      imgEl.src = e.target.result;
      imgEl.setAttribute("width", 160);
      imgEl.setAttribute("height", 160);
      document.body.append(imgEl);
      const fromPixels = tf.browser.fromPixels(imgEl);
      resolve(fromPixels);
    };
    reader.onerror = reject;
    reader.readAsDataURL(imgFile);
  });
};

图像被正确地附加到文档主体。 imageElement的形式为: <img src="data:image/jpeg;base64,....." width=160 height=160>

1 个答案:

答案 0 :(得分:1)

当尚未加载public Statistics getNextStatistics() throws ProfilingException { AsyncResultCallback<Statistics> callback = new AsyncResultCallback<>(); client.statsCmd(containerId).exec(callback); Statistics stats; try { stats = callback.awaitResult(); callback.close(); } catch (RuntimeException | IOException e) { // you may want to throw an exception here } return stats; // this may be null or invalid if the container has terminated } 标签时,您正在从图像创建张量。这是要走的路

img