node.jstensorflowtensorflow.jstfjs-node

How do I load a batch of images to be processed by my tfjs model


I've created a model in Keras and converted it to a Tensorflow.js model and loaded it into my node.js project. And now I want to get predictions from this model in Tensorflow.js. I have figured out how to load a single image:

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

This creates a single tensor of shape (imageWidth, imageHeight, 3). But I want to load a batch of images into a tensor with a shape (batchNumber, imageWidth, imageHeight, 3).

How would I go about doing that?


Solution

  • If you want to add a batch dimension to your image, you can use 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)
    

    If you want to create a batch of multiple images, you can use 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)