issue1038 / nodejs /onnxruntime.js
jrsimuix's picture
onnxruntime-node test
6ea0f1f verified
raw
history blame
1.03 kB
const fs = require('fs');
const sharp = require('sharp');
const ort = require('onnxruntime-node');
(async () => {
try {
// Step 1: Load and preprocess the image
const imageBuffer = await sharp('./training_images/shirt/00e745c9-97d9-429d-8c3f-d3db7a2d2991.jpg')
.resize(128, 128) // Resize to 128x128
.raw() // Get raw pixel data
.toBuffer();
// Convert to Float32 and normalize pixel values to [0, 1]
const imgArray = Float32Array.from(imageBuffer).map(value => value / 255.0);
// Add batch dimension [1, 128, 128, 3]
const inputTensor = new ort.Tensor('float32', imgArray, [1, 128, 128, 3]);
// Step 2: Load ONNX model
const session = await ort.InferenceSession.create('./saved-model/model.onnx');
// Step 3: Run inference
const results = await session.run({ [session.inputNames[0]]: inputTensor });
console.log('Inference outputs:', results[session.outputNames[0]]);
} catch (err) {
console.error('Error:', err);
}
})();