image2tags
Version:
An npm package that generates keywords from an image
27 lines (26 loc) • 1.03 kB
JavaScript
import * as tf from '@tensorflow/tfjs-node';
import * as mobilenet from '@tensorflow-models/mobilenet';
import * as fs from 'fs';
import { promisify } from 'util';
const readFile = promisify(fs.readFile);
let modelCache = null;
async function loadModel() {
if (!modelCache) {
modelCache = await mobilenet.load();
}
return modelCache;
}
export async function getImageTags(imagePath, topK = 10) {
try {
const image = await readFile(imagePath);
const imageTensor = tf.node.decodeImage(new Uint8Array(image), 3);
const model = await loadModel();
const predictions = await model.classify(imageTensor);
const processedPredictions = predictions.map((p) => (Object.assign(Object.assign({}, p), { tags: p.className.split(',').map((s) => s.trim()) })));
return processedPredictions.slice(0, topK);
}
catch (error) {
console.error('An error occurred while processing the image:', error);
throw new Error('Could not classify the image.');
}
}