<file_sep># Image Classification
Image classification using [TensorFlowJS](https://www.tensorflow.org/js) and Angular 10 by file upload or by webcam streaming. The [MobileNet](https://github.com/tensorflow/tfjs-models/tree/master/mobilenet) model is used to classify the image element and the streaming video element.

File upload:

* After choosing an image, the image will be loaded and the model will classify the image returning the top three predictions for that image.
  
Webcam Streaming:

* When the webcam is turned on, the video streaming will begin and the model will classify the HTMLVideoElement returning the top three predictions for that video element every three seconds.
<file_sep>import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import * as mobilenet from '@tensorflow-models/mobilenet';
import * as tf from '@tensorflow/tfjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'image-classification';

  model;
  isVideo: boolean;
  isImage: boolean;
  imgSrc: string;
  @ViewChild('img') imageEl: ElementRef;
  @ViewChild('video') video: ElementRef;
  predictions: Prediction[];

  ngOnInit(){
    console.log('loading mobilenet model...');
    tf.setBackend('cpu').then(async () => {
      this.model = await mobilenet.load();
    });
    console.log('Sucessfully loaded model');
  }

  streamVideo(){
    this.isImage = false;
    this.isVideo = true;
    if (navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
          this.video.nativeElement.srcObject = stream;
        })
        .catch((error) => {
          console.log('Something went wrong!');
        });
    }
    setInterval(async () => {
      this.predictions = await this.model.classify(this.video.nativeElement);
      await tf.nextFrame();
    }, 3000);
  }

  turnOffWebcam(){
    this.video.nativeElement.srcObject.getVideoTracks()[0].stop();
    this.isVideo = false;
  }

  fileChange(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();

      reader.readAsDataURL(file);

      reader.onload = (res: any) => {
        this.isImage = true;
        this.imgSrc = res.target.result;
        setTimeout(async () => {
          this.predictions = await this.model.classify(this.imageEl.nativeElement);
        });
      };
    }
  }
}

export interface Prediction {
  className: string;
  probability: number;
}