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

时间:2020-10-28 15:50:33

标签: image tensorflow tensorflow.js

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

1 个答案:

答案 0 :(得分:1)

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