object-detection.service.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { Injectable, Logger } from '@nestjs/common';
  2. import * as cocoSsd from '@tensorflow-models/coco-ssd';
  3. import * as tf from '@tensorflow/tfjs-node';
  4. import * as fs from 'fs';
  5. @Injectable()
  6. export class ObjectDetectionService {
  7. private cocoSsdModel: cocoSsd.ObjectDetection;
  8. constructor() {
  9. Logger.log(
  10. `Running Node TensorFlow Version : ${tf.version['tfjs']}`,
  11. 'ObjectDetection',
  12. );
  13. cocoSsd.load().then((model) => (this.cocoSsdModel = model));
  14. }
  15. async detectObject(thumbnailPath: string) {
  16. try {
  17. const isExist = fs.existsSync(thumbnailPath);
  18. if (isExist) {
  19. const tags = new Set();
  20. const image = fs.readFileSync(thumbnailPath);
  21. const decodedImage = tf.node.decodeImage(image, 3) as tf.Tensor3D;
  22. const predictions = await this.cocoSsdModel.detect(decodedImage);
  23. for (const result of predictions) {
  24. if (result.score > 0.5) {
  25. tags.add(result.class);
  26. }
  27. }
  28. tf.dispose(decodedImage);
  29. return [...tags];
  30. }
  31. } catch (e) {
  32. console.log('Error reading file ', e);
  33. }
  34. }
  35. }