output label and confidence
Browse files- nodejs/onnxruntime.js +12 -5
nodejs/onnxruntime.js
CHANGED
@@ -5,15 +5,13 @@ const ort = require('onnxruntime-node');
|
|
5 |
(async () => {
|
6 |
try {
|
7 |
// Step 1: Load and preprocess the image
|
8 |
-
const imageBuffer = await sharp('./training_images/
|
9 |
.resize(128, 128) // Resize to 128x128
|
10 |
.raw() // Get raw pixel data
|
11 |
.toBuffer();
|
12 |
|
13 |
-
//
|
14 |
const imgArray = Float32Array.from(imageBuffer).map(value => value / 255.0);
|
15 |
-
|
16 |
-
// Add batch dimension [1, 128, 128, 3]
|
17 |
const inputTensor = new ort.Tensor('float32', imgArray, [1, 128, 128, 3]);
|
18 |
|
19 |
// Step 2: Load ONNX model
|
@@ -22,7 +20,16 @@ const ort = require('onnxruntime-node');
|
|
22 |
// Step 3: Run inference
|
23 |
const results = await session.run({ [session.inputNames[0]]: inputTensor });
|
24 |
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
} catch (err) {
|
27 |
console.error('Error:', err);
|
28 |
}
|
|
|
5 |
(async () => {
|
6 |
try {
|
7 |
// Step 1: Load and preprocess the image
|
8 |
+
const imageBuffer = await sharp('./training_images/hat.jpg')
|
9 |
.resize(128, 128) // Resize to 128x128
|
10 |
.raw() // Get raw pixel data
|
11 |
.toBuffer();
|
12 |
|
13 |
+
// Normalize to [0, 1] and create input tensor
|
14 |
const imgArray = Float32Array.from(imageBuffer).map(value => value / 255.0);
|
|
|
|
|
15 |
const inputTensor = new ort.Tensor('float32', imgArray, [1, 128, 128, 3]);
|
16 |
|
17 |
// Step 2: Load ONNX model
|
|
|
20 |
// Step 3: Run inference
|
21 |
const results = await session.run({ [session.inputNames[0]]: inputTensor });
|
22 |
|
23 |
+
// Step 4: Get output probabilities
|
24 |
+
const probabilities = results[session.outputNames[0]].data; // Float32Array
|
25 |
+
const labelIndex = probabilities.indexOf(Math.max(...probabilities)); // Find the index of the max probability
|
26 |
+
|
27 |
+
// Step 5: Load the label map
|
28 |
+
const labelMap = JSON.parse(fs.readFileSync('./labelMap.json', 'utf8')); // Assuming you saved the label map
|
29 |
+
const label = Object.keys(labelMap).find(key => labelMap[key] === labelIndex);
|
30 |
+
|
31 |
+
console.log(`Predicted label: ${label}`);
|
32 |
+
console.log(`Confidencex: ${(probabilities[labelIndex] * 100).toFixed(2)}%`);
|
33 |
} catch (err) {
|
34 |
console.error('Error:', err);
|
35 |
}
|