Given the url, how to load an image and then transform it into a tf.tensor data in Javascript?

Viewed 957

I am new to frontend and javascript. Now I am writing a CNN-based web application. To load an image from the given url, and then feed the image into a CNN, I tried to write the following codes:

async function getImage() {
  var img = new Image();
  img.src = 'https://www.google.com/favicon.ico';
  var output = tf.browser.fromPixels(img);
  return output;
}

Unfortunately it didn't work ;(

How do I load the image and transform it into a tf.tensor? Could somebody help me achieve my goal?

1 Answers

The tensor has to be created once the image has completed to be loaded

async function getImage() {
  var img = new Image();
  img.src = 'https://www.google.com/favicon.ico';

  img.onload = () => {
  var output = tf.browser.fromPixels(img);
  return output;
  }

}
Related