-
-
Save cuongdev/201148277e7d5c0adf19a955f3b710a0 to your computer and use it in GitHub Desktop.
Image Prediction on tfjs-node (with model made by Teachable Machine Image)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tf = require('@tensorflow/tfjs-node'); | |
const Jimp = require('jimp'); | |
// Path for model file | |
// NOTE: It can be obtained from [Export Model] -> [Tensorflow.js] -> [Download my model] | |
// on https://teachablemachine.withgoogle.com/train/image | |
const MODEL_FILE = `${__dirname}/model.json`; | |
// Path for image file to predict class | |
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(); | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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