如何从图像中获取张量
How to get a tensor from an image
我有一张图片,我想从中获取张量。
一些图像已经在前端服务器上,而其他图像将由服务器提供
为此,需要使用 fromPixels
如果图像已经显示在 html 页面中
你可以考虑做一个 querySelector 先获取图像然后你可以使用 fromPixels
html
<img id="my-image" src="mydata.jpg">
js
const image = document.querySelector("#my-image")
const t = tf.fromPixels(image)
如果 html 页面中没有图片,可以使用构造函数 Image 创建它,然后将其作为参数传递给 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 确保图像在转换为张量之前已完成下载。
如果提供前端页面的图像 url 和 url 不同,则在创建张量时会出现 cross-origin 问题。如果服务器使用允许前端检索该图像的访问控制来提供图像,则设置图像的 crossOrigin
属性将解决问题,否则无法从中获取张量图片。
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>
我有一张图片,我想从中获取张量。
一些图像已经在前端服务器上,而其他图像将由服务器提供
为此,需要使用 fromPixels
如果图像已经显示在 html 页面中 你可以考虑做一个 querySelector 先获取图像然后你可以使用 fromPixels
html
<img id="my-image" src="mydata.jpg">
js
const image = document.querySelector("#my-image")
const t = tf.fromPixels(image)
如果 html 页面中没有图片,可以使用构造函数 Image 创建它,然后将其作为参数传递给 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 确保图像在转换为张量之前已完成下载。
如果提供前端页面的图像 url 和 url 不同,则在创建张量时会出现 cross-origin 问题。如果服务器使用允许前端检索该图像的访问控制来提供图像,则设置图像的 crossOrigin
属性将解决问题,否则无法从中获取张量图片。
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>