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

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

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.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.7.0"> </script>
  5. <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@1.5.1/dist/tfjs-vis.umd.min.js"></script>
  6. <title>display image</title>
  7. </head>
  8. <body>
  9. <input type="file" accept="image/*" onchange="loadFile(event)">
  10. <p id="result">Prediction </p>
  11. <p><img id="output" width="200"/></p>
  12. <script>
  13. var loadFile = function(event) {
  14. var image = document.getElementById('output');
  15. image.src=URL.createObjectURL(event.target.files[0]);
  16. };
  17. //Some method to convert the image into a tensor
  18. </script>
  19. </body>
  20. </html>

答案1

得分: 0

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

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

Did you check tf.browser.fromPixels ?

  1. image.onload = () => {
  2. const imgTensor = tf.browser.fromPixels(image);
  3. ...
  4. }

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:

确定