如何加载一批图像以供我的 tfjs 模型处理

the*_*ker 2 node.js tensorflow tensorflow.js tfjs-node

我在 Keras 中创建了一个模型,并将其转换为 Tensorflow.js 模型,并将其加载到我的 node.js 项目中。现在我想从 Tensorflow.js 中的这个模型中获得预测。我已经弄清楚如何加载单个图像:

var singleImageData = fs.readFileSync('path/to/image.jpeg');
var image = tf.node.decodeImage(new Uint8Array(singleImageData), 3);
image = tf.cast(image, 'float32');
//other image processing
Run Code Online (Sandbox Code Playgroud)

这将创建一个形状为 的张量(imageWidth, imageHeight, 3)。但我想将一批图像加载到具有 shape 的张量中(batchNumber, imageWidth, imageHeight, 3)

我该怎么做呢?

Les*_*rel 5

如果您想向图像添加批量尺寸,可以使用tf.expandDims

// let say that image has the following shape: (32,32,3)
imageWithBatchDim = image.expandDims(0)
// imageWithBatchDim has the following shape: (1,32,32,3)
Run Code Online (Sandbox Code Playgroud)

如果你想创建一批多张图像,你可以使用tf.stack

// image1 and image2 must have the same shape (i.e (32,32,3))
batchImages = tf.stack([image1, image2])
// batchImages will have the following shape: (2,32,32,3)
Run Code Online (Sandbox Code Playgroud)