如何使用Tensorflow.js tf.image.cropAndResize从HTML Canvas、Image或Video元素中裁剪和调整图像大小?

393 阅读1分钟

这是一个快速的帖子,展示如何使用tf. image.cropAndResize函数将图像裁剪并调整为方形。

这个函数是为一个特定的目的而创建的,即切出一个人脸检测算法所给出的边界框。但你也可以把它用于其他目的

你的图像可以来自HTML Canvas、HTML Image或甚至HTML Video元素。
首先,我们使用tf.browser.fromPixels
将其转换为张量。

 let imageTensor = tf.browser.fromPixels(imageData);

其中imageData: (tf.PixelData | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)

由于图像的像素值为[0, 255],我们需要对其进行标准化处理。

const offset = tf.scalar(255.0);
const normalized = imageTensor.div(offset);

现在我们几乎已经准备好使用tf.image.cropAndResize()函数了。

tf.image.cropAndResize (image, boxes, boxInd, cropSize, method?, extrapolationValue?)

参数:

  • image:一个分批的张量(4-D),即一个要以张量格式调整大小的标准化图像列表。
  • boxes:一个在裁剪中使用的盒子的列表。每个盒子指定坐标为[上,左,下,右]。这些坐标是标准化的,这意味着它们必须在[0,1]之间。
  • boxInd - 1D Tensorf,指定盒子所指的图像的索引。
  • cropSize - 这控制了图像裁剪后的宽度和高度。

在这个例子中,取自我为演示快速风格转换而创建的Tensorflow.js小工具,我们正在调整一张图片的大小,并将其裁剪成一个正方形。

const imgSize = Math.min(imageData.width, imageData.height);
const left = (imageData.width - imgSize) / 2;
const top = (imageData.height - imgSize) / 2;
const right = (imageData.width + imgSize) / 2;
const bottom = (imageData.height + imgSize) / 2;
let boxes = [[top / imageData.height, left / imageData.width, bottom / imageData.height, right / imageData.width]];
result = tf.image.cropAndResize(batched, boxes, [0], [size,size])

你可以查看Github资源库,看看这个函数的运行情况。

github.com/armindocach…

资源: Tensorflow.js API文档js.tensorflow.org/api/latest/…