MCPcopy Create free account
hub / github.com/tensorflow/tfjs-examples / ImageClassifier

Class ImageClassifier

electron/image_classifier.js:33–187  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

31 * dataset and can be seen in `./imagenet_classes.js`.
32 */
33export class ImageClassifier {
34 constructor() {
35 this.model = null;
36 }
37
38 /**
39 * Perform classification on a batch of image tensors.
40 *
41 * @param {tf.Tensor} images Batch image tensor of shape
42 * `[numExamples, height, width, channels]`. The values of `height`,
43 * `width` and `channel` must match the underlying MobileNetV2 model
44 * (default: 224, 224, 3).
45 * @param {number} topK How many results with top probability / logit values
46 * to return for each example.
47 * @return {Array<{className: string, prob: number}>} An array of classes
48 * with the highest `topK` probability scores, sorted in the descending
49 * order of the probability scores. Each element of the array corresponds
50 * to one example in `images`. The order of the elements matches that
51 * of `images`.
52 */
53 async classify(images, topK = 5) {
54 await this.ensureModelLoaded();
55 return tf.tidy(() => {
56 const probs = this.model.predict(images);
57 const sorted = true;
58 const {values, indices} = tf.topk(probs, topK, sorted);
59
60 const classProbs = values.arraySync();
61 const classIndices = indices.arraySync();
62
63 const results = [];
64 classIndices.forEach((indices, i) => {
65 const classesAndProbs = [];
66 indices.forEach((index, j) => {
67 classesAndProbs.push({
68 className: IMAGENET_CLASSES[index],
69 prob: classProbs[i][j]
70 });
71 });
72 results.push(classesAndProbs);
73 })
74
75 return results;
76 });
77 }
78
79 /**
80 * If the underlying model is not loaded, load it.
81 *
82 * @param {() => any} loadingCallback An optional callback function that will
83 * be invoked when the model is being loaded.
84 */
85 async ensureModelLoaded(loadingCallback) {
86 if (this.model == null) {
87 console.log('Loading image classifier model...');
88 if (loadingCallback != null) {
89 loadingCallback();
90 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected