TensorFlowJS 无法加载 JS 生成的图像

TensorFlowJS fails to load a JS generated image

TensorFlowJS 可以从 HTML 加载图像,但通常无法从 JavaScript 生成的图像对象加载图像。

代码如下。第一组加载方式可以从HTML加载图片。

h = document.getElementById("dandelion");
let image1 = await tf.browser.fromPixels(h);
var x1 = document.createElement("CANVAS");
tf.browser.toPixels(image1, x1);
document.body.append(x1);

第二组加载方式会生成一个online_img和一个link的在线图片。但是当我尝试绘制加载的图像时,我只得到一个黑色方块。

let online_img = await document.createElement("IMG"); 
online_img.setAttribute("id", "loaded_image")
online_img.setAttribute("src", str);
online_img.setAttribute("width", "200");
online_img.setAttribute("height", "100");
await document.body.appendChild(online_img);
let image = await tf.browser.fromPixels(online_img);
var x = document.createElement("CANVAS");
tf.browser.toPixels(image, x);
document.body.append(x);

所以我想知道是否有任何方法可以通过第二组方法成功加载图像

谢谢!!

此处提供了完整的 HTML 代码。

<html>
<script src="https://unpkg.com/@tensorflow/tfjs"> </script>
<head></head>
<body>
 <img id="dandelion" crossorigin height="320" width="480" src="https://images-na.ssl-images-amazon.com/images/I/719fF478nPL._SX425_.jpg"></img>
</body>
<script>
async function getImage_online(str){
  // load and draw from html: success. 
//   const image1 = tf.browser.fromPixels(dandelion);
  h = document.getElementById("dandelion");
  let image1 = await tf.browser.fromPixels(h);
  var x1 = document.createElement("CANVAS");
  tf.browser.toPixels(image1, x1);
  document.body.append(x1);

  // load the image from generated image: loaded image is black. 
  let online_img = await document.createElement("IMG"); 
  online_img.setAttribute("id", "loaded_image")
  online_img.setAttribute("src", str);
  online_img.setAttribute("width", "200");
  online_img.setAttribute("height", "100");
  await document.body.appendChild(online_img);
  let image = await tf.browser.fromPixels(online_img);
  var x = document.createElement("CANVAS");
  tf.browser.toPixels(image, x);
  document.body.append(x);

}

async function newRun_online(){
  let c = await getImage_online("https://images-na.ssl-images-amazon.com/images/I/719fF478nPL._SX425_.jpg"); // c: rose
}

newRun_online(); 

</script>
</html>

加载图片失败,因为之前图片还没有完成加载。

image.onload = () => {
  tf.browser.toPixels(image, x);
}