Skip to content

Commit c4861ea

Browse files
authored
[image classifier ] Fix memory leak in image classifier (#697)
* uses tidy to fix mem leak in imageClassifier * sends in raw image vs tensor to predict * send in processed tensor to classify
1 parent c666ac3 commit c4861ea

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/ImageClassifier/index.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ class ImageClassifier {
130130
* @return {object} an object with {label, confidence}.
131131
*/
132132
async classifyInternal(imgToPredict, numberOfClasses) {
133-
133+
134134
// Wait for the model to be ready
135135
await this.ready;
136136
await tf.nextFrame();
@@ -152,14 +152,15 @@ class ImageClassifier {
152152

153153
// Process the images
154154
const imageResize = [IMAGE_SIZE, IMAGE_SIZE];
155-
const processedImg = imgToTensor(imgToPredict, imageResize);
156-
155+
157156
if (this.modelUrl) {
158157
await tf.nextFrame();
159158
const predictedClasses = tf.tidy(() => {
159+
const processedImg = imgToTensor(imgToPredict, imageResize);
160160
const predictions = this.model.predict(processedImg);
161161
return Array.from(predictions.as1D().dataSync());
162162
});
163+
163164
const results = await predictedClasses.map((confidence, index) => {
164165
const label = (this.mapStringToIndex.length > 0 && this.mapStringToIndex[index]) ? this.mapStringToIndex[index] : index;
165166
return {
@@ -168,15 +169,16 @@ class ImageClassifier {
168169
};
169170
}).sort((a, b) => b.confidence - a.confidence);
170171
return results;
171-
}
172+
}
172173

173-
const result = this.model
174+
const processedImg = imgToTensor(imgToPredict, imageResize);
175+
const results = this.model
174176
.classify(processedImg, numberOfClasses)
175177
.then(classes => classes.map(c => ({ label: c.className, confidence: c.probability })));
176178

177179
processedImg.dispose();
178-
179-
return result;
180+
181+
return results;
180182
}
181183

182184
/**

0 commit comments

Comments
 (0)