首页 > 解决方案 > 将路径图像转换为新张量为 [1, 224, 224, 3] 形状

问题描述

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

标签: imagetensorflowtensorflow.js

解决方案


下面是一个 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
}

推荐阅读