-
Notifications
You must be signed in to change notification settings - Fork 82
/
main.dart
409 lines (382 loc) · 11.8 KB
/
main.dart
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:camera/camera.dart';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:flutter/material.dart';
import 'detector_painters.dart';
import 'utils.dart';
import 'package:image/image.dart' as imglib;
import 'package:tflite_flutter/tflite_flutter.dart' as tfl;
import 'package:quiver/collection.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(brightness: Brightness.light),
home: _MyHomePage(),
title: "Face Recognition",
debugShowCheckedModeBanner: false,
));
}
class _MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<_MyHomePage> {
File jsonFile;
dynamic _scanResults;
CameraController _camera;
var interpreter;
bool _isDetecting = false;
CameraLensDirection _direction = CameraLensDirection.front;
dynamic data = {};
double threshold = 1.0;
Directory tempDir;
List e1;
bool _faceFound = false;
final TextEditingController _name = new TextEditingController();
@override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
_initializeCamera();
}
Future loadModel() async {
try {
final gpuDelegateV2 = tfl.GpuDelegateV2(
options: tfl.GpuDelegateOptionsV2(
false,
tfl.TfLiteGpuInferenceUsage.fastSingleAnswer,
tfl.TfLiteGpuInferencePriority.minLatency,
tfl.TfLiteGpuInferencePriority.auto,
tfl.TfLiteGpuInferencePriority.auto,
));
var interpreterOptions = tfl.InterpreterOptions()
..addDelegate(gpuDelegateV2);
interpreter = await tfl.Interpreter.fromAsset('mobilefacenet.tflite',
options: interpreterOptions);
} on Exception {
print('Failed to load model.');
}
}
void _initializeCamera() async {
await loadModel();
CameraDescription description = await getCamera(_direction);
ImageRotation rotation = rotationIntToImageRotation(
description.sensorOrientation,
);
_camera =
CameraController(description, ResolutionPreset.low, enableAudio: false);
await _camera.initialize();
await Future.delayed(Duration(milliseconds: 500));
tempDir = await getApplicationDocumentsDirectory();
String _embPath = tempDir.path + '/emb.json';
jsonFile = new File(_embPath);
if (jsonFile.existsSync()) data = json.decode(jsonFile.readAsStringSync());
_camera.startImageStream((CameraImage image) {
if (_camera != null) {
if (_isDetecting) return;
_isDetecting = true;
String res;
dynamic finalResult = Multimap<String, Face>();
detect(image, _getDetectionMethod(), rotation).then(
(dynamic result) async {
if (result.length == 0)
_faceFound = false;
else
_faceFound = true;
Face _face;
imglib.Image convertedImage =
_convertCameraImage(image, _direction);
for (_face in result) {
double x, y, w, h;
x = (_face.boundingBox.left - 10);
y = (_face.boundingBox.top - 10);
w = (_face.boundingBox.width + 10);
h = (_face.boundingBox.height + 10);
imglib.Image croppedImage = imglib.copyCrop(
convertedImage, x.round(), y.round(), w.round(), h.round());
croppedImage = imglib.copyResizeCropSquare(croppedImage, 112);
// int startTime = new DateTime.now().millisecondsSinceEpoch;
res = _recog(croppedImage);
// int endTime = new DateTime.now().millisecondsSinceEpoch;
// print("Inference took ${endTime - startTime}ms");
finalResult.add(res, _face);
}
setState(() {
_scanResults = finalResult;
});
_isDetecting = false;
},
).catchError(
(_) {
_isDetecting = false;
},
);
}
});
}
HandleDetection _getDetectionMethod() {
final faceDetector = FirebaseVision.instance.faceDetector(
FaceDetectorOptions(
mode: FaceDetectorMode.accurate,
),
);
return faceDetector.processImage;
}
Widget _buildResults() {
const Text noResultsText = const Text('');
if (_scanResults == null ||
_camera == null ||
!_camera.value.isInitialized) {
return noResultsText;
}
CustomPainter painter;
final Size imageSize = Size(
_camera.value.previewSize.height,
_camera.value.previewSize.width,
);
painter = FaceDetectorPainter(imageSize, _scanResults);
return CustomPaint(
painter: painter,
);
}
Widget _buildImage() {
if (_camera == null || !_camera.value.isInitialized) {
return Center(
child: CircularProgressIndicator(),
);
}
return Container(
constraints: const BoxConstraints.expand(),
child: _camera == null
? const Center(child: null)
: Stack(
fit: StackFit.expand,
children: <Widget>[
CameraPreview(_camera),
_buildResults(),
],
),
);
}
void _toggleCameraDirection() async {
if (_direction == CameraLensDirection.back) {
_direction = CameraLensDirection.front;
} else {
_direction = CameraLensDirection.back;
}
await _camera.stopImageStream();
await _camera.dispose();
setState(() {
_camera = null;
});
_initializeCamera();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Face recognition'),
actions: <Widget>[
PopupMenuButton<Choice>(
onSelected: (Choice result) {
if (result == Choice.delete)
_resetFile();
else
_viewLabels();
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<Choice>>[
const PopupMenuItem<Choice>(
child: Text('View Saved Faces'),
value: Choice.view,
),
const PopupMenuItem<Choice>(
child: Text('Remove all faces'),
value: Choice.delete,
)
],
),
],
),
body: _buildImage(),
floatingActionButton:
Column(mainAxisAlignment: MainAxisAlignment.end, children: [
FloatingActionButton(
backgroundColor: (_faceFound) ? Colors.blue : Colors.blueGrey,
child: Icon(Icons.add),
onPressed: () {
if (_faceFound) _addLabel();
},
heroTag: null,
),
SizedBox(
height: 10,
),
FloatingActionButton(
onPressed: _toggleCameraDirection,
heroTag: null,
child: _direction == CameraLensDirection.back
? const Icon(Icons.camera_front)
: const Icon(Icons.camera_rear),
),
]),
);
}
imglib.Image _convertCameraImage(
CameraImage image, CameraLensDirection _dir) {
int width = image.width;
int height = image.height;
// imglib -> Image package from https://pub.dartlang.org/packages/image
var img = imglib.Image(width, height); // Create Image buffer
const int hexFF = 0xFF000000;
final int uvyButtonStride = image.planes[1].bytesPerRow;
final int uvPixelStride = image.planes[1].bytesPerPixel;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
final int uvIndex =
uvPixelStride * (x / 2).floor() + uvyButtonStride * (y / 2).floor();
final int index = y * width + x;
final yp = image.planes[0].bytes[index];
final up = image.planes[1].bytes[uvIndex];
final vp = image.planes[2].bytes[uvIndex];
// Calculate pixel color
int r = (yp + vp * 1436 / 1024 - 179).round().clamp(0, 255);
int g = (yp - up * 46549 / 131072 + 44 - vp * 93604 / 131072 + 91)
.round()
.clamp(0, 255);
int b = (yp + up * 1814 / 1024 - 227).round().clamp(0, 255);
// color: 0x FF FF FF FF
// A B G R
img.data[index] = hexFF | (b << 16) | (g << 8) | r;
}
}
var img1 = (_dir == CameraLensDirection.front)
? imglib.copyRotate(img, -90)
: imglib.copyRotate(img, 90);
return img1;
}
String _recog(imglib.Image img) {
List input = imageToByteListFloat32(img, 112, 128, 128);
input = input.reshape([1, 112, 112, 3]);
List output = List(1 * 192).reshape([1, 192]);
interpreter.run(input, output);
output = output.reshape([192]);
e1 = List.from(output);
return compare(e1).toUpperCase();
}
String compare(List currEmb) {
if (data.length == 0) return "No Face saved";
double minDist = 999;
double currDist = 0.0;
String predRes = "NOT RECOGNIZED";
for (String label in data.keys) {
currDist = euclideanDistance(data[label], currEmb);
if (currDist <= threshold && currDist < minDist) {
minDist = currDist;
predRes = label;
}
}
print(minDist.toString() + " " + predRes);
return predRes;
}
void _resetFile() {
data = {};
jsonFile.deleteSync();
}
void _viewLabels() {
setState(() {
_camera = null;
});
String name;
var alert = new AlertDialog(
title: new Text("Saved Faces"),
content: new ListView.builder(
padding: new EdgeInsets.all(2),
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
name = data.keys.elementAt(index);
return new Column(
children: <Widget>[
new ListTile(
title: new Text(
name,
style: new TextStyle(
fontSize: 14,
color: Colors.grey[400],
),
),
),
new Padding(
padding: EdgeInsets.all(2),
),
new Divider(),
],
);
}),
actions: <Widget>[
new FlatButton(
child: Text("OK"),
onPressed: () {
_initializeCamera();
Navigator.pop(context);
},
)
],
);
showDialog(
context: context,
builder: (context) {
return alert;
});
}
void _addLabel() {
setState(() {
_camera = null;
});
print("Adding new face");
var alert = new AlertDialog(
title: new Text("Add Face"),
content: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
controller: _name,
autofocus: true,
decoration: new InputDecoration(
labelText: "Name", icon: new Icon(Icons.face)),
),
)
],
),
actions: <Widget>[
new FlatButton(
child: Text("Save"),
onPressed: () {
_handle(_name.text.toUpperCase());
_name.clear();
Navigator.pop(context);
}),
new FlatButton(
child: Text("Cancel"),
onPressed: () {
_initializeCamera();
Navigator.pop(context);
},
)
],
);
showDialog(
context: context,
builder: (context) {
return alert;
});
}
void _handle(String text) {
data[text] = e1;
jsonFile.writeAsStringSync(json.encode(data));
_initializeCamera();
}
}