Converting path image to new Tensor to a [1, 224, 224, 3] shape

Viewed 848

I use this Python code to convert a giving image path to a new Tensor. How can I do the same in TensorFlow JS with Node.js?

  def process_image(image_path):
     # Read in image file
     image = tf.io.read_file(image_path)
     # Turn the jpeg image into numerical Tensor with 3 colour channels (Red, Green, Blue)
     image = tf.image.decode_jpeg(image, channels=3)
     # Convert the colour channel values from 0-225 values to 0-1 values
     image = tf.image.convert_image_dtype(image, tf.float32)
     # Resize the image to our desired size (224, 244)
     image = tf.image.resize(image, size=[IMG_SIZE, IMG_SIZE])
     return image
1 Answers

Below is a js function that will do the same processing as in python

const tfnode = require('@tensorflow/tfjs-node')
function processImage(path) {

    const imageSize = 224
    const imageBuffer =  fs.readFileSync(path); // can also use the async readFile instead
    // get tensor out of the buffer
    image = tfnode.node.decodeImage(imageBuffer, 3);
    // dtype to float
    image = image.cast('float32').div(255);
    // resize the image
    image = tf.image.resizeBilinear(image, size = [imageSize, imageSize]); // can also use tf.image.resizeNearestNeighbor
    image = image.expandDims(); // to add the most left axis of size 1
    return image.shape
}
Related