如何在JavaScript和HTML中将图像转换为张量?

huangapple go评论52阅读模式
英文:

How to convert image to tensor in Javascript and HTML?

问题

我试图创建一个网页,在这个网页上我可以选择并显示一张本地图片,以及由TensorFlow模型生成的预测。要将图像馈送给模型,它需要以每个像素的值为基础的张量。我该如何将图像转换为像素值的张量?下面是示例代码。

英文:

I'm trying to create a webpage where I can select and display a local image, alongside a prediction made by a TensorFlow model. To feed the image to the model it needs to be in a tensor with values for each pixel. How can I convert the image to a tensor of pixel values? The example code is below.

<!DOCTYPE html>
<html>
  <head>
      <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.7.0"> </script>

      <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@1.5.1/dist/tfjs-vis.umd.min.js"></script>
    <title>display image</title>
  </head>
  <body>
      <input type="file" accept="image/*" onchange="loadFile(event)">
      <p id="result">Prediction </p>
      <p><img id="output" width="200"/></p>
      <script>
          var loadFile = function(event) {
              var image = document.getElementById('output');
              image.src=URL.createObjectURL(event.target.files[0]);
          };
          //Some method to convert the image into a tensor
      </script>
  </body>
</html>

答案1

得分: 0

你有检查过tf.browser.fromPixels吗?

image.onload = () => {
  const imgTensor = tf.browser.fromPixels(image);
  ...
}
英文:

Did you check tf.browser.fromPixels ?

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

huangapple
  • 本文由 发表于 2023年7月3日 07:36:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定