Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cuongdev/201148277e7d5c0adf19a955f3b710a0 to your computer and use it in GitHub Desktop.
Save cuongdev/201148277e7d5c0adf19a955f3b710a0 to your computer and use it in GitHub Desktop.
Image Prediction on tfjs-node (with model made by Teachable Machine Image)
const tf = require('@tensorflow/tfjs-node');
const Jimp = require('jimp');
const MODEL_FILE = `${__dirname}/model.json`;
const IMAGE_FILE = `${__dirname}/example.jpg`;
(async () => {
const model = await tf.loadLayersModel(`file://${MODEL_FILE}`);
model.summary();
const image = await Jimp.read(`${IMAGE_FILE}`);
image.cover(224, 224, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE);
image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => {
const pixel = Jimp.intToRGBA(image.getPixelColor(x, y));
pixel.r = Math.max(0.0, pixel.r / 127.0 - 1);
pixel.g = Math.max(0.0, pixel.g / 127.0 - 1);
pixel.b = Math.max(0.0, pixel.b / 127.0 - 1);
pixel.a = Math.max(0.0, pixel.a / 127.0 - 1);
image.setPixelColor(Jimp.rgbaToInt(pixel.r, pixel.g, pixel.b, pixel.a), x, y);
});
const buffer = await image.getBufferAsync(Jimp.MIME_JPEG);
let img_tensor = tf.node.decodeImage(new Uint8Array(buffer), 3);
img_tensor = img_tensor.expandDims(0);
const predictions = await model.predict(img_tensor);
predictions.print();
})();
{
"name": "image-predict-on-tfjs-node",
"description": "Prediction using tfjs-node (with model made by Teachable Machine Image)",
"scripts": {
"start": "node image-predict-on-tfjs-node.js"
},
"engines": {
"node": "14"
},
"dependencies": {
"jimp": "^0.12.1",
"@tensorflow/tfjs-node": "^1.3.1",
},
"devDependencies": {
},
"private": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment