将图像Jimp到Tensor node.js

2024-10-03 19:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Tensorflow.js模型。模型以Jimp格式接收图像

我需要将Jimp位图转换为4d张量

到目前为止,我已经尝试了这个toTensor函数:

function imageByteArray (image){
    
    const numChannels = 3;

    const numPixels = image.bitmap.width * image.bitmap.height;
    const values = new Int32Array(numPixels * numChannels);


    image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx){

        values[y * image.bitmap.width * numChannels + x * numChannels + 0] = this.bitmap.data[idx + 0];
        values[y * image.bitmap.width * numChannels + x * numChannels + 1] = this.bitmap.data[idx + 1];
        values[y * image.bitmap.width * numChannels + x * numChannels + 2] = this.bitmap.data[idx + 2];

    });


    return values
}
  
function toTensor(image){
    const values = imageByteArray(image);
    // const values = image.data;
    const outShape = [1, image.bitmap.height, image.bitmap.width, 3];
    const input = tf.tensor4d(values, outShape, 'float32');

    return input.sub(127.5).div(128.0)

}

但当我使用python比较原始预处理(在培训阶段实现)时cv2

def process(image):

    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image = image.astype("float32")

    image = (image - 127.5) / 128.0


    return image.reshape((1, width, height, 3))

但在输入方面存在一些小的差异

Is there any correct method to convert jimp image to RGB tensor


Tags: 模型imagedatareturnfunctionthiswidthcv2
2条回答

tf.node可以允许对位图编码图像进行解码,如本answer中所示

const img = fs.readFileSync("path/of/image");
const tensor = tf.node.decodeImage(img)

我找到了一种将jimp图像转换为tfnode.Tensor的方法:

function preProcess(image){
    // const values = imageByteArray(image);
    const values = image.bitmap.data;
    const outShape = [1, image.bitmap.width, image.bitmap.height, 4];
    var input = tf.tensor4d(values, outShape, 'float32');
    
    // Slice away alpha
    input = input.slice([0, 0, 0, 0], [1, image.bitmap.width, image.bitmap.height, 3]);


    return input;

}

Jimp图像通常也包含alpha值,所以我也生成了包含alpha值的4D张量,然后只包含slicedRGB值

正如@Edkeveke所说。我可以使用tf.node.decodeImage功能,但我的主要预处理(在培训期间)是在opencv上进行的,所以我需要确保它尽可能接近opencv实现

我还发现了一些带有tensorflow图像函数的problems

所以我选择不使用tensorflow图像函数

相关问题 更多 >