javascript - TensorFlowJS 无法加载 JS 生成的图像

标签 javascript html tensorflow tensorflow.js

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 ,其中包含在线图像的链接。但是当我尝试绘制加载的图像时,我只得到一个黑色方 block 。

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);
}

关于javascript - TensorFlowJS 无法加载 JS 生成的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59433143/

相关文章:

php - 通过 AJAX 发送输入数组

javascript - Primefaces GMap addMarker (JavaScript) + selectMarker (overlaySelectEvent)

javascript - 鼠标输入时 react 显示按钮

javascript - 使用 jquery 验证函数不适用于选择元素

javascript - 使用 jQuery GET 在 JSON 文件中获取属性的问题

html - 让表格随着扩展的 div 垂直增长

html - 如何设置Vue Core UI选择值

python - 如何匹配tensorflow(python)函数的参数

python - Python利用文件路径

tensorflow - 如何恢复 LSTM 层