将路径图像转换为新的 Tensor 为 [1, 224, 224, 3] 形状

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

我使用此 Python 代码将给定的图像路径转换为新的张量。如何使用 Node.js 在 TensorFlow 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

下面是一个 js 函数,它将执行与 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
}