如何从图像中获取张量 [英] How to get a tensor from an image

查看:49
本文介绍了如何从图像中获取张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像,我想从中获取张量.

有些图像已经在前端服务器上,而其他图像将由服务器提供

解决方案

要做到这一点,需要使用 创建它,然后将其作为参数传递给 从像素

const im = new Image()im.onload = () =>{const a = tf.fromPixels(im, 4)打印()console.log(a.shape)}im.src =图片的网址";document.body.appendChild(im)

onload 确保图像在将其转换为张量之前已完成下载.

如果图像 url 和提供前端页面的 url 不同,则会出现 cross-origin 问题.如果服务器使用允许前端检索该图像的访问控制来提供图像,则设置图像的 crossOrigin 属性将解决问题,否则将无法获取来自该图像的张量.

const im = new Image()im.crossOrigin = "匿名";im.src = "https://i.imgur.com/lVlPvCB.gif"document.body.appendChild(im)im.onload = () =>{const a = tf.fromPixels(im, 4)打印()console.log(a.shape)}

<头><!-- 加载 TensorFlow.js --><script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"><身体></html>

I have an image and I would like to get the tensor from it.

Some of the images are already on the frontend server be whereas others will be served by the server

解决方案

To do that, one needs to use fromPixels

In case the image is already displayed in an html page You can consider doing a querySelector to get the image first and then you can use fromPixels

html

<img id="my-image" src="mydata.jpg">

js

const image = document.querySelector("#my-image")
const t = tf.fromPixels(image)

If the image is not present in the html page, you can use the constructor Image to create it and then pass it as parameter to fromPixels

const im = new Image()
im.onload = () => {
  const a = tf.fromPixels(im, 4)
  a.print()
  console.log(a.shape)
}
im.src = "url-of-the-image"
document.body.appendChild(im)

onload makes sure that the image has finished downloading before converting it to a tensor.

If the image url and the url on which the frontend page is served are different there will be a cross-origin issue when creating the tensor. If the server serves the image with an access control that allows the frontend to retrieve that image, then setting the crossOrigin attribute of the image will solve the issue, otherwise there will nothing that can be done to get the tensor from that image.

const im = new Image()
im.crossOrigin = "anonymous";
im.src = "https://i.imgur.com/lVlPvCB.gif"
document.body.appendChild(im)
im.onload = () => {
  const a = tf.fromPixels(im, 4)
  a.print()
  console.log(a.shape)
}

<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
  </head>

  <body>
  </body>
</html>

这篇关于如何从图像中获取张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆