-
Notifications
You must be signed in to change notification settings - Fork 23
/
face-detection.component.ts
159 lines (150 loc) · 5.66 KB
/
face-detection.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { NgOpenCVService, OpenCVLoadResult } from 'ng-open-cv';
import { tap, switchMap, filter } from 'rxjs/operators';
import { forkJoin, Observable, empty, fromEvent, BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-face-detection',
templateUrl: './face-detection.component.html',
styleUrls: ['./face-detection.component.css']
})
export class FaceDetectionComponent implements AfterViewInit, OnInit {
imageUrl = 'assets/DaveChappelle.jpg';
// Notifies of the ready state of the classifiers load operation
private classifiersLoaded = new BehaviorSubject<boolean>(false);
classifiersLoaded$ = this.classifiersLoaded.asObservable();
// HTML Element references
@ViewChild('fileInput')
fileInput: ElementRef;
@ViewChild('canvasInput')
canvasInput: ElementRef;
@ViewChild('canvasOutput')
canvasOutput: ElementRef;
// Inject the NgOpenCVService
constructor(private ngOpenCVService: NgOpenCVService) {}
ngOnInit() {
// Always subscribe to the NgOpenCVService isReady$ observer before using a CV related function to ensure that the OpenCV has been
// successfully loaded
this.ngOpenCVService.isReady$
.pipe(
// The OpenCV library has been successfully loaded if result.ready === true
filter((result: OpenCVLoadResult) => result.ready),
switchMap(() => {
// Load the face and eye classifiers files
return this.loadClassifiers();
})
)
.subscribe(() => {
// The classifiers have been succesfully loaded
this.classifiersLoaded.next(true);
});
}
ngAfterViewInit(): void {
// Here we just load our example image to the canvas
this.ngOpenCVService.isReady$
.pipe(
filter((result: OpenCVLoadResult) => result.ready),
tap((result: OpenCVLoadResult) => {
this.ngOpenCVService.loadImageToHTMLCanvas(this.imageUrl, this.canvasInput.nativeElement).subscribe();
})
)
.subscribe(() => {});
}
readDataUrl(event) {
if (event.target.files.length) {
const reader = new FileReader();
const load$ = fromEvent(reader, 'load');
load$
.pipe(
switchMap(() => {
return this.ngOpenCVService.loadImageToHTMLCanvas(`${reader.result}`, this.canvasInput.nativeElement);
})
)
.subscribe(
() => {},
err => {
console.log('Error loading image', err);
}
);
reader.readAsDataURL(event.target.files[0]);
}
}
// Before attempting face detection, we need to load the appropriate classifiers in memory first
// by using the createFileFromUrl(path, url) function, which takes two parameters
// @path: The path you will later use in the detectMultiScale function call
// @url: The url where to retrieve the file from.
loadClassifiers(): Observable<any> {
return forkJoin(
this.ngOpenCVService.createFileFromUrl(
'haarcascade_frontalface_default.xml',
`assets/opencv/data/haarcascades/haarcascade_frontalface_default.xml`
),
this.ngOpenCVService.createFileFromUrl(
'haarcascade_eye.xml',
`assets/opencv/data/haarcascades/haarcascade_eye.xml`
)
);
}
detectFace() {
// before detecting the face we need to make sure that
// 1. OpenCV is loaded
// 2. The classifiers have been loaded
this.ngOpenCVService.isReady$
.pipe(
filter((result: OpenCVLoadResult) => result.ready),
switchMap(() => {
return this.classifiersLoaded$;
}),
tap(() => {
this.clearOutputCanvas();
this.findFaceAndEyes();
})
)
.subscribe(() => {
console.log('Face detected');
});
}
clearOutputCanvas() {
const context = this.canvasOutput.nativeElement.getContext('2d');
context.clearRect(0, 0, this.canvasOutput.nativeElement.width, this.canvasOutput.nativeElement.height);
}
findFaceAndEyes() {
// Example code from OpenCV.js to perform face and eyes detection
// Slight adapted for Angular
const src = cv.imread(this.canvasInput.nativeElement.id);
const gray = new cv.Mat();
cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY, 0);
const faces = new cv.RectVector();
const eyes = new cv.RectVector();
const faceCascade = new cv.CascadeClassifier();
const eyeCascade = new cv.CascadeClassifier();
// load pre-trained classifiers, they should be in memory now
faceCascade.load('haarcascade_frontalface_default.xml');
eyeCascade.load('haarcascade_eye.xml');
// detect faces
const msize = new cv.Size(0, 0);
faceCascade.detectMultiScale(gray, faces, 1.1, 3, 0, msize, msize);
for (let i = 0; i < faces.size(); ++i) {
const roiGray = gray.roi(faces.get(i));
const roiSrc = src.roi(faces.get(i));
const point1 = new cv.Point(faces.get(i).x, faces.get(i).y);
const point2 = new cv.Point(faces.get(i).x + faces.get(i).width, faces.get(i).y + faces.get(i).height);
cv.rectangle(src, point1, point2, [255, 0, 0, 255]);
// detect eyes in face ROI
eyeCascade.detectMultiScale(roiGray, eyes);
for (let j = 0; j < eyes.size(); ++j) {
const point3 = new cv.Point(eyes.get(j).x, eyes.get(j).y);
const point4 = new cv.Point(eyes.get(j).x + eyes.get(j).width, eyes.get(j).y + eyes.get(j).height);
cv.rectangle(roiSrc, point3, point4, [0, 0, 255, 255]);
}
roiGray.delete();
roiSrc.delete();
}
cv.imshow(this.canvasOutput.nativeElement.id, src);
src.delete();
gray.delete();
faceCascade.delete();
eyeCascade.delete();
faces.delete();
eyes.delete();
}
}