face recognition on ios release, works fine on depug but blank screen on release.
I’m using this package
text
and google mlk face reconizer
The feature works fine on android, and on ios depug, but when i release it on ios, it show blank sncree.
here is my screen
<code>class FaceRegistrationScreen extends StatefulWidget {
final bool toInterview;
const FaceRegistrationScreen({super.key, this.toInterview = false});
@override
State<FaceRegistrationScreen> createState() => _FaceRegistrationState();
}
class _FaceRegistrationState extends State<FaceRegistrationScreen> {
ImagePicker imagePicker = ImagePicker();
File? _image;
late FaceDetector faceDetector;
late Recognizer recognizer;
bool loading = false;
List<Face> faces = [];
var image;
@override
void initState() {
super.initState();
final options = FaceDetectorOptions();
faceDetector = FaceDetector(options: options);
recognizer = Recognizer();
}
removeRotation(File inputImage) async {
final img.Image? capturedImage =
img.decodeImage(await File(inputImage.path).readAsBytes());
final img.Image orientedImage = img.bakeOrientation(capturedImage!);
return await File(_image!.path).writeAsBytes(img.encodeJpg(orientedImage));
}
doFaceDetection() async {
_image = await removeRotation(_image!);
image = await _image?.readAsBytes();
image = await decodeImageFromList(image);
setState(() {
image;
});
InputImage inputImage = InputImage.fromFile(_image!);
faces = await faceDetector.processImage(inputImage).then((value) async {
if (value.isNotEmpty) {
Rect faceRect = value[0].boundingBox;
num left = faceRect.left < 0 ? 0 : faceRect.left;
num top = faceRect.top < 0 ? 0 : faceRect.top;
num right =
faceRect.right > image.width ? image.width - 1 : faceRect.right;
num bottom =
faceRect.bottom > image.height ? image.height - 1 : faceRect.bottom;
num width = right - left;
num height = bottom - top;
final bytes = _image!.readAsBytesSync();
img.Image? faceImg = img.decodeImage(bytes);
img.Image faceImg2 = img.copyCrop(faceImg!,
x: left.toInt(),
y: top.toInt(),
width: width.toInt(),
height: height.toInt());
List<double> emb = recognizer.getEmbedding(faceImg2, faceRect);
await AppPreferences.setUserEmbedding(emb.join(",")).then(
(value) async => await uploadUserImage(
context, _image!, EndPoints.saveUserImage,
toInterview: widget.toInterview));
} else {
myToast(
context: context,
text: AppStrings.pleaseLookCameraWhenTakingPhoto,
state: ToastStates.error);
}
return value;
});
setState(() {
_image;
faces;
loading = false;
});
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Stack(
children: [
myBackgroundContainer(context),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
mySigningAppBar(context, AppStrings.logInSubTitleFace),
Expanded(
child: Card(
child: SizedBox(
height: double.infinity,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: AppSize.s10.h,
),
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(AppPadding.p20.r),
child: _column()),
),
),
],
),
),
),
),
],
),
],
),
),
),
);
}
Widget _column() => Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
image != null
? Column(
children: [
Container(
margin: EdgeInsets.all(AppMargin.m30.r),
padding: EdgeInsets.only(bottom: AppSize.s93.h),
child: FittedBox(
child: SizedBox(
width: image.width.toDouble(),
height: image.width.toDouble(),
child: CustomPaint(
painter:
FacePainter(facesList: faces, imageFile: image),
),
),
),
),
SizedBox(
height: AppSize.s60.h,
),
(loading)
? SizedBox(
height: AppSize.s50.spMin,
width: 1.sw,
child: const Center(
child: CircularProgressIndicator(),
),
)
: SizedBox(
width: image.width.toDouble(),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: myElevatedButton(context,
text: AppStrings.tryAgain, onPressed: () {
setState(() {
image = null;
});
}),
),
SizedBox(
width: AppSize.s20.w,
),
Expanded(
child: myElevatedButton(context,
text: AppStrings.uploadPhotoAnyway,
onPressed: () async {
if (_image != null) {
await uploadUserImage(context, _image!,
EndPoints.saveUserImage,
toInterview: widget.toInterview);
}
}),
),
],
),
),
],
)
: SmartFaceCameraWidget(
loading: loading,
showCameraLensControl: true,
onCapture: (File? img) async {
setState(() {
_image = img;
loading = true;
});
await doFaceDetection();
},
),
SizedBox(
height: AppSize.s40.h,
),
],
);
}
class FacePainter extends CustomPainter {
List<Face> facesList;
dynamic imageFile;
FacePainter({required this.facesList, @required this.imageFile});
@override
void paint(Canvas canvas, Size size) {
if (imageFile != null) {
canvas.drawImage(imageFile, Offset.zero, Paint());
}
Paint p = Paint();
p.color = Colors.red;
p.style = PaintingStyle.stroke;
p.strokeWidth = 6;
for (Face face in facesList) {
canvas.drawRect(face.boundingBox, p);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
</code>
<code>class FaceRegistrationScreen extends StatefulWidget {
final bool toInterview;
const FaceRegistrationScreen({super.key, this.toInterview = false});
@override
State<FaceRegistrationScreen> createState() => _FaceRegistrationState();
}
class _FaceRegistrationState extends State<FaceRegistrationScreen> {
ImagePicker imagePicker = ImagePicker();
File? _image;
late FaceDetector faceDetector;
late Recognizer recognizer;
bool loading = false;
List<Face> faces = [];
var image;
@override
void initState() {
super.initState();
final options = FaceDetectorOptions();
faceDetector = FaceDetector(options: options);
recognizer = Recognizer();
}
removeRotation(File inputImage) async {
final img.Image? capturedImage =
img.decodeImage(await File(inputImage.path).readAsBytes());
final img.Image orientedImage = img.bakeOrientation(capturedImage!);
return await File(_image!.path).writeAsBytes(img.encodeJpg(orientedImage));
}
doFaceDetection() async {
_image = await removeRotation(_image!);
image = await _image?.readAsBytes();
image = await decodeImageFromList(image);
setState(() {
image;
});
InputImage inputImage = InputImage.fromFile(_image!);
faces = await faceDetector.processImage(inputImage).then((value) async {
if (value.isNotEmpty) {
Rect faceRect = value[0].boundingBox;
num left = faceRect.left < 0 ? 0 : faceRect.left;
num top = faceRect.top < 0 ? 0 : faceRect.top;
num right =
faceRect.right > image.width ? image.width - 1 : faceRect.right;
num bottom =
faceRect.bottom > image.height ? image.height - 1 : faceRect.bottom;
num width = right - left;
num height = bottom - top;
final bytes = _image!.readAsBytesSync();
img.Image? faceImg = img.decodeImage(bytes);
img.Image faceImg2 = img.copyCrop(faceImg!,
x: left.toInt(),
y: top.toInt(),
width: width.toInt(),
height: height.toInt());
List<double> emb = recognizer.getEmbedding(faceImg2, faceRect);
await AppPreferences.setUserEmbedding(emb.join(",")).then(
(value) async => await uploadUserImage(
context, _image!, EndPoints.saveUserImage,
toInterview: widget.toInterview));
} else {
myToast(
context: context,
text: AppStrings.pleaseLookCameraWhenTakingPhoto,
state: ToastStates.error);
}
return value;
});
setState(() {
_image;
faces;
loading = false;
});
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Stack(
children: [
myBackgroundContainer(context),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
mySigningAppBar(context, AppStrings.logInSubTitleFace),
Expanded(
child: Card(
child: SizedBox(
height: double.infinity,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: AppSize.s10.h,
),
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(AppPadding.p20.r),
child: _column()),
),
),
],
),
),
),
),
],
),
],
),
),
),
);
}
Widget _column() => Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
image != null
? Column(
children: [
Container(
margin: EdgeInsets.all(AppMargin.m30.r),
padding: EdgeInsets.only(bottom: AppSize.s93.h),
child: FittedBox(
child: SizedBox(
width: image.width.toDouble(),
height: image.width.toDouble(),
child: CustomPaint(
painter:
FacePainter(facesList: faces, imageFile: image),
),
),
),
),
SizedBox(
height: AppSize.s60.h,
),
(loading)
? SizedBox(
height: AppSize.s50.spMin,
width: 1.sw,
child: const Center(
child: CircularProgressIndicator(),
),
)
: SizedBox(
width: image.width.toDouble(),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: myElevatedButton(context,
text: AppStrings.tryAgain, onPressed: () {
setState(() {
image = null;
});
}),
),
SizedBox(
width: AppSize.s20.w,
),
Expanded(
child: myElevatedButton(context,
text: AppStrings.uploadPhotoAnyway,
onPressed: () async {
if (_image != null) {
await uploadUserImage(context, _image!,
EndPoints.saveUserImage,
toInterview: widget.toInterview);
}
}),
),
],
),
),
],
)
: SmartFaceCameraWidget(
loading: loading,
showCameraLensControl: true,
onCapture: (File? img) async {
setState(() {
_image = img;
loading = true;
});
await doFaceDetection();
},
),
SizedBox(
height: AppSize.s40.h,
),
],
);
}
class FacePainter extends CustomPainter {
List<Face> facesList;
dynamic imageFile;
FacePainter({required this.facesList, @required this.imageFile});
@override
void paint(Canvas canvas, Size size) {
if (imageFile != null) {
canvas.drawImage(imageFile, Offset.zero, Paint());
}
Paint p = Paint();
p.color = Colors.red;
p.style = PaintingStyle.stroke;
p.strokeWidth = 6;
for (Face face in facesList) {
canvas.drawRect(face.boundingBox, p);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
</code>
class FaceRegistrationScreen extends StatefulWidget {
final bool toInterview;
const FaceRegistrationScreen({super.key, this.toInterview = false});
@override
State<FaceRegistrationScreen> createState() => _FaceRegistrationState();
}
class _FaceRegistrationState extends State<FaceRegistrationScreen> {
ImagePicker imagePicker = ImagePicker();
File? _image;
late FaceDetector faceDetector;
late Recognizer recognizer;
bool loading = false;
List<Face> faces = [];
var image;
@override
void initState() {
super.initState();
final options = FaceDetectorOptions();
faceDetector = FaceDetector(options: options);
recognizer = Recognizer();
}
removeRotation(File inputImage) async {
final img.Image? capturedImage =
img.decodeImage(await File(inputImage.path).readAsBytes());
final img.Image orientedImage = img.bakeOrientation(capturedImage!);
return await File(_image!.path).writeAsBytes(img.encodeJpg(orientedImage));
}
doFaceDetection() async {
_image = await removeRotation(_image!);
image = await _image?.readAsBytes();
image = await decodeImageFromList(image);
setState(() {
image;
});
InputImage inputImage = InputImage.fromFile(_image!);
faces = await faceDetector.processImage(inputImage).then((value) async {
if (value.isNotEmpty) {
Rect faceRect = value[0].boundingBox;
num left = faceRect.left < 0 ? 0 : faceRect.left;
num top = faceRect.top < 0 ? 0 : faceRect.top;
num right =
faceRect.right > image.width ? image.width - 1 : faceRect.right;
num bottom =
faceRect.bottom > image.height ? image.height - 1 : faceRect.bottom;
num width = right - left;
num height = bottom - top;
final bytes = _image!.readAsBytesSync();
img.Image? faceImg = img.decodeImage(bytes);
img.Image faceImg2 = img.copyCrop(faceImg!,
x: left.toInt(),
y: top.toInt(),
width: width.toInt(),
height: height.toInt());
List<double> emb = recognizer.getEmbedding(faceImg2, faceRect);
await AppPreferences.setUserEmbedding(emb.join(",")).then(
(value) async => await uploadUserImage(
context, _image!, EndPoints.saveUserImage,
toInterview: widget.toInterview));
} else {
myToast(
context: context,
text: AppStrings.pleaseLookCameraWhenTakingPhoto,
state: ToastStates.error);
}
return value;
});
setState(() {
_image;
faces;
loading = false;
});
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Stack(
children: [
myBackgroundContainer(context),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
mySigningAppBar(context, AppStrings.logInSubTitleFace),
Expanded(
child: Card(
child: SizedBox(
height: double.infinity,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: AppSize.s10.h,
),
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(AppPadding.p20.r),
child: _column()),
),
),
],
),
),
),
),
],
),
],
),
),
),
);
}
Widget _column() => Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
image != null
? Column(
children: [
Container(
margin: EdgeInsets.all(AppMargin.m30.r),
padding: EdgeInsets.only(bottom: AppSize.s93.h),
child: FittedBox(
child: SizedBox(
width: image.width.toDouble(),
height: image.width.toDouble(),
child: CustomPaint(
painter:
FacePainter(facesList: faces, imageFile: image),
),
),
),
),
SizedBox(
height: AppSize.s60.h,
),
(loading)
? SizedBox(
height: AppSize.s50.spMin,
width: 1.sw,
child: const Center(
child: CircularProgressIndicator(),
),
)
: SizedBox(
width: image.width.toDouble(),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: myElevatedButton(context,
text: AppStrings.tryAgain, onPressed: () {
setState(() {
image = null;
});
}),
),
SizedBox(
width: AppSize.s20.w,
),
Expanded(
child: myElevatedButton(context,
text: AppStrings.uploadPhotoAnyway,
onPressed: () async {
if (_image != null) {
await uploadUserImage(context, _image!,
EndPoints.saveUserImage,
toInterview: widget.toInterview);
}
}),
),
],
),
),
],
)
: SmartFaceCameraWidget(
loading: loading,
showCameraLensControl: true,
onCapture: (File? img) async {
setState(() {
_image = img;
loading = true;
});
await doFaceDetection();
},
),
SizedBox(
height: AppSize.s40.h,
),
],
);
}
class FacePainter extends CustomPainter {
List<Face> facesList;
dynamic imageFile;
FacePainter({required this.facesList, @required this.imageFile});
@override
void paint(Canvas canvas, Size size) {
if (imageFile != null) {
canvas.drawImage(imageFile, Offset.zero, Paint());
}
Paint p = Paint();
p.color = Colors.red;
p.style = PaintingStyle.stroke;
p.strokeWidth = 6;
for (Face face in facesList) {
canvas.drawRect(face.boundingBox, p);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
and the smart face camera widget
<code>class SmartFaceCameraWidget extends StatefulWidget {
final bool loading;
final bool showCameraLensControl;
final void Function(File?) onCapture;
const SmartFaceCameraWidget({
super.key,
this.loading = false,
required this.showCameraLensControl,
required this.onCapture,
});
@override
SmartFaceCameraWidgetState createState() => SmartFaceCameraWidgetState();
}
class SmartFaceCameraWidgetState extends State<SmartFaceCameraWidget> {
late FaceCameraController _controller;
@override
void initState() {
super.initState();
_controller = FaceCameraController(
onCapture: widget.onCapture,
defaultCameraLens: CameraLens.front,
);
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
height: 600.h,
child: SmartFaceCamera(
controller: _controller,
showCaptureControl: true,
showFlashControl: false,
showCameraLensControl: widget.showCameraLensControl,
captureControlBuilder: (context, _) {
return widget.loading
? SizedBox(
height: AppSize.s54.h,
child: const Center(child: CircularProgressIndicator()),
)
: Container(
alignment: Alignment.center,
width: AppSize.s200.w,
height: AppSize.s54.h,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppSize.s20),
color: AppColors.primary,
),
padding: EdgeInsets.symmetric(
horizontal: AppPadding.p8.w, vertical: AppPadding.p2.h),
child: Text(
AppStrings.captureImageCamera,
textAlign: TextAlign.center,
style: getAppSemiBoldTextStyle(
color: AppColors.white, fontSize: FontSize.s16.spMin),
),
);
},
lensControlIcon: CircleAvatar(
backgroundColor: AppColors.white,
radius: AppSize.s26.r,
child: Icon(
Icons.cameraswitch,
size: AppSize.s40.r,
color: AppColors.primary,
),
),
messageBuilder: (context, face) {
if (face == null) {
return _message('ضع وجهك أمام الكاميرا');
}
if (!face.wellPositioned) {
return _message('قم بتوسيط وجهك في المربع');
}
return const SizedBox.shrink();
},
),
);
}
Widget _message(String msg) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 55, vertical: 15),
child: Text(
msg,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
height: 1.5,
fontWeight: FontWeight.w400,
),
),
);
}
</code>
<code>class SmartFaceCameraWidget extends StatefulWidget {
final bool loading;
final bool showCameraLensControl;
final void Function(File?) onCapture;
const SmartFaceCameraWidget({
super.key,
this.loading = false,
required this.showCameraLensControl,
required this.onCapture,
});
@override
SmartFaceCameraWidgetState createState() => SmartFaceCameraWidgetState();
}
class SmartFaceCameraWidgetState extends State<SmartFaceCameraWidget> {
late FaceCameraController _controller;
@override
void initState() {
super.initState();
_controller = FaceCameraController(
onCapture: widget.onCapture,
defaultCameraLens: CameraLens.front,
);
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
height: 600.h,
child: SmartFaceCamera(
controller: _controller,
showCaptureControl: true,
showFlashControl: false,
showCameraLensControl: widget.showCameraLensControl,
captureControlBuilder: (context, _) {
return widget.loading
? SizedBox(
height: AppSize.s54.h,
child: const Center(child: CircularProgressIndicator()),
)
: Container(
alignment: Alignment.center,
width: AppSize.s200.w,
height: AppSize.s54.h,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppSize.s20),
color: AppColors.primary,
),
padding: EdgeInsets.symmetric(
horizontal: AppPadding.p8.w, vertical: AppPadding.p2.h),
child: Text(
AppStrings.captureImageCamera,
textAlign: TextAlign.center,
style: getAppSemiBoldTextStyle(
color: AppColors.white, fontSize: FontSize.s16.spMin),
),
);
},
lensControlIcon: CircleAvatar(
backgroundColor: AppColors.white,
radius: AppSize.s26.r,
child: Icon(
Icons.cameraswitch,
size: AppSize.s40.r,
color: AppColors.primary,
),
),
messageBuilder: (context, face) {
if (face == null) {
return _message('ضع وجهك أمام الكاميرا');
}
if (!face.wellPositioned) {
return _message('قم بتوسيط وجهك في المربع');
}
return const SizedBox.shrink();
},
),
);
}
Widget _message(String msg) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 55, vertical: 15),
child: Text(
msg,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
height: 1.5,
fontWeight: FontWeight.w400,
),
),
);
}
</code>
class SmartFaceCameraWidget extends StatefulWidget {
final bool loading;
final bool showCameraLensControl;
final void Function(File?) onCapture;
const SmartFaceCameraWidget({
super.key,
this.loading = false,
required this.showCameraLensControl,
required this.onCapture,
});
@override
SmartFaceCameraWidgetState createState() => SmartFaceCameraWidgetState();
}
class SmartFaceCameraWidgetState extends State<SmartFaceCameraWidget> {
late FaceCameraController _controller;
@override
void initState() {
super.initState();
_controller = FaceCameraController(
onCapture: widget.onCapture,
defaultCameraLens: CameraLens.front,
);
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
height: 600.h,
child: SmartFaceCamera(
controller: _controller,
showCaptureControl: true,
showFlashControl: false,
showCameraLensControl: widget.showCameraLensControl,
captureControlBuilder: (context, _) {
return widget.loading
? SizedBox(
height: AppSize.s54.h,
child: const Center(child: CircularProgressIndicator()),
)
: Container(
alignment: Alignment.center,
width: AppSize.s200.w,
height: AppSize.s54.h,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppSize.s20),
color: AppColors.primary,
),
padding: EdgeInsets.symmetric(
horizontal: AppPadding.p8.w, vertical: AppPadding.p2.h),
child: Text(
AppStrings.captureImageCamera,
textAlign: TextAlign.center,
style: getAppSemiBoldTextStyle(
color: AppColors.white, fontSize: FontSize.s16.spMin),
),
);
},
lensControlIcon: CircleAvatar(
backgroundColor: AppColors.white,
radius: AppSize.s26.r,
child: Icon(
Icons.cameraswitch,
size: AppSize.s40.r,
color: AppColors.primary,
),
),
messageBuilder: (context, face) {
if (face == null) {
return _message('ضع وجهك أمام الكاميرا');
}
if (!face.wellPositioned) {
return _message('قم بتوسيط وجهك في المربع');
}
return const SizedBox.shrink();
},
),
);
}
Widget _message(String msg) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 55, vertical: 15),
child: Text(
msg,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
height: 1.5,
fontWeight: FontWeight.w400,
),
),
);
}
and this is my recognizer
<code>class Recognizer {
late Interpreter interpreter;
late InterpreterOptions _interpreterOptions;
static const int WIDTH = 160;
static const int HEIGHT = 160;
Map<String,Recognition> registered = {};
// String get modelName => 'assets/mobile_face_net.tflite';
String get modelName => 'assets/facenet.tflite';
Recognizer({int? numThreads}) {
_interpreterOptions = InterpreterOptions();
if (numThreads != null) {
_interpreterOptions.threads = numThreads;
}
loadModel();
}
void registerFaceInDB(context , List<double> embedding) async {
AppPreferences.setUserEmbedding(embedding.join(",")) ;
// debugPrint("embedding ${AppConstants.embedding}" );
// GoRouter.of(context).go( Routes.homeRout );
}
Future<void> loadModel() async {
try {
interpreter = await Interpreter.fromAsset(modelName);
} catch (e) {
debugPrint('Unable to create interpreter, Caught Exception: ${e.toString()}');
}
}
List<dynamic> imageToArray(img.Image inputImage){
img.Image resizedImage = img.copyResize(inputImage, width: WIDTH, height: HEIGHT);
List<double> flattenedList = resizedImage.data!.expand(
(channel) => [channel.r, channel.g, channel.b]).map(
(value) => value.toDouble()).toList();
Float32List float32Array = Float32List.fromList(flattenedList);
int channels = 3;
int height = HEIGHT;
int width = WIDTH;
Float32List reshapedArray = Float32List(1 * height * width * channels);
for (int c = 0; c < channels; c++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int index = c * height * width + h * width + w;
reshapedArray[index] = (float32Array[c * height * width + h * width + w]-127.5)/127.5;
}
}
}
// return reshapedArray.reshape([1,112,112,3]);
return reshapedArray.reshape([1,160,160,3]);
}
Recognition recognize(img.Image image, Rect location) {
//TODO crop face from image resize it and convert it to float array
var input = imageToArray(image);
debugPrint(input.shape.toString());
//TODO output array
// List output = List.filled(1*192, 0).reshape([1,192]);
List output = List.filled(1*512, 0).reshape([1,512]);
//TODO performs inference
final runs = DateTime.now().millisecondsSinceEpoch;
interpreter.run(input, output);
final run = DateTime.now().millisecondsSinceEpoch - runs;
debugPrint('Time to run inference: $run ms$output');
//TODO convert dynamic list to double list
List<double> outputArray = output.first.cast<double>();
//TODO looks for the nearest embeeding in the database and returns the pair
Pair pair = findNearest(outputArray);
debugPrint("distance= ${pair.distance}");
return Recognition(pair.name,location,outputArray,pair.distance);
}
List<double> getEmbedding(img.Image image, Rect location) {
//TODO crop face from image resize it and convert it to float array
var input = imageToArray(image);
debugPrint(input.shape.toString());
//TODO output array
// List output = List.filled(1*192, 0).reshape([1,192]);
List output = List.filled(1*512, 0).reshape([1,512]);
//TODO performs inference
final runs = DateTime.now().millisecondsSinceEpoch;
interpreter.run(input, output);
final run = DateTime.now().millisecondsSinceEpoch - runs;
debugPrint('Time to run inference: $run ms$output');
//TODO convert dynamic list to double list
return output.first.cast<double>();
}
//TODO looks for the nearest embeeding in the database and returns the pair which contain information of registered face with which face is most similar
findNearest(List<double> emb){
Pair pair = Pair(" ليست ${UserData.fullName} ", -5);
// for (MapEntry<String, Recognition> item in registered.entries) {
// final String name = item.key;
List<double> knownEmb = AppConstants.embedding ; //item.value.embeddings;
double distance = 0;
for (int i = 0; i < emb.length; i++) {
double diff = emb[i] -
knownEmb[i];
distance += diff*diff;
}
distance = sqrt(distance);
if (pair.distance == -5 || distance < pair.distance) {
pair.distance = distance;
if( distance < 1) pair.name = UserData.fullName;
}
// }
return pair;
}
void close() {
interpreter.close();
}
}
class Pair{
String name;
double distance;
Pair(this.name,this.distance);
}
</code>
<code>class Recognizer {
late Interpreter interpreter;
late InterpreterOptions _interpreterOptions;
static const int WIDTH = 160;
static const int HEIGHT = 160;
Map<String,Recognition> registered = {};
// String get modelName => 'assets/mobile_face_net.tflite';
String get modelName => 'assets/facenet.tflite';
Recognizer({int? numThreads}) {
_interpreterOptions = InterpreterOptions();
if (numThreads != null) {
_interpreterOptions.threads = numThreads;
}
loadModel();
}
void registerFaceInDB(context , List<double> embedding) async {
AppPreferences.setUserEmbedding(embedding.join(",")) ;
// debugPrint("embedding ${AppConstants.embedding}" );
// GoRouter.of(context).go( Routes.homeRout );
}
Future<void> loadModel() async {
try {
interpreter = await Interpreter.fromAsset(modelName);
} catch (e) {
debugPrint('Unable to create interpreter, Caught Exception: ${e.toString()}');
}
}
List<dynamic> imageToArray(img.Image inputImage){
img.Image resizedImage = img.copyResize(inputImage, width: WIDTH, height: HEIGHT);
List<double> flattenedList = resizedImage.data!.expand(
(channel) => [channel.r, channel.g, channel.b]).map(
(value) => value.toDouble()).toList();
Float32List float32Array = Float32List.fromList(flattenedList);
int channels = 3;
int height = HEIGHT;
int width = WIDTH;
Float32List reshapedArray = Float32List(1 * height * width * channels);
for (int c = 0; c < channels; c++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int index = c * height * width + h * width + w;
reshapedArray[index] = (float32Array[c * height * width + h * width + w]-127.5)/127.5;
}
}
}
// return reshapedArray.reshape([1,112,112,3]);
return reshapedArray.reshape([1,160,160,3]);
}
Recognition recognize(img.Image image, Rect location) {
//TODO crop face from image resize it and convert it to float array
var input = imageToArray(image);
debugPrint(input.shape.toString());
//TODO output array
// List output = List.filled(1*192, 0).reshape([1,192]);
List output = List.filled(1*512, 0).reshape([1,512]);
//TODO performs inference
final runs = DateTime.now().millisecondsSinceEpoch;
interpreter.run(input, output);
final run = DateTime.now().millisecondsSinceEpoch - runs;
debugPrint('Time to run inference: $run ms$output');
//TODO convert dynamic list to double list
List<double> outputArray = output.first.cast<double>();
//TODO looks for the nearest embeeding in the database and returns the pair
Pair pair = findNearest(outputArray);
debugPrint("distance= ${pair.distance}");
return Recognition(pair.name,location,outputArray,pair.distance);
}
List<double> getEmbedding(img.Image image, Rect location) {
//TODO crop face from image resize it and convert it to float array
var input = imageToArray(image);
debugPrint(input.shape.toString());
//TODO output array
// List output = List.filled(1*192, 0).reshape([1,192]);
List output = List.filled(1*512, 0).reshape([1,512]);
//TODO performs inference
final runs = DateTime.now().millisecondsSinceEpoch;
interpreter.run(input, output);
final run = DateTime.now().millisecondsSinceEpoch - runs;
debugPrint('Time to run inference: $run ms$output');
//TODO convert dynamic list to double list
return output.first.cast<double>();
}
//TODO looks for the nearest embeeding in the database and returns the pair which contain information of registered face with which face is most similar
findNearest(List<double> emb){
Pair pair = Pair(" ليست ${UserData.fullName} ", -5);
// for (MapEntry<String, Recognition> item in registered.entries) {
// final String name = item.key;
List<double> knownEmb = AppConstants.embedding ; //item.value.embeddings;
double distance = 0;
for (int i = 0; i < emb.length; i++) {
double diff = emb[i] -
knownEmb[i];
distance += diff*diff;
}
distance = sqrt(distance);
if (pair.distance == -5 || distance < pair.distance) {
pair.distance = distance;
if( distance < 1) pair.name = UserData.fullName;
}
// }
return pair;
}
void close() {
interpreter.close();
}
}
class Pair{
String name;
double distance;
Pair(this.name,this.distance);
}
</code>
class Recognizer {
late Interpreter interpreter;
late InterpreterOptions _interpreterOptions;
static const int WIDTH = 160;
static const int HEIGHT = 160;
Map<String,Recognition> registered = {};
// String get modelName => 'assets/mobile_face_net.tflite';
String get modelName => 'assets/facenet.tflite';
Recognizer({int? numThreads}) {
_interpreterOptions = InterpreterOptions();
if (numThreads != null) {
_interpreterOptions.threads = numThreads;
}
loadModel();
}
void registerFaceInDB(context , List<double> embedding) async {
AppPreferences.setUserEmbedding(embedding.join(",")) ;
// debugPrint("embedding ${AppConstants.embedding}" );
// GoRouter.of(context).go( Routes.homeRout );
}
Future<void> loadModel() async {
try {
interpreter = await Interpreter.fromAsset(modelName);
} catch (e) {
debugPrint('Unable to create interpreter, Caught Exception: ${e.toString()}');
}
}
List<dynamic> imageToArray(img.Image inputImage){
img.Image resizedImage = img.copyResize(inputImage, width: WIDTH, height: HEIGHT);
List<double> flattenedList = resizedImage.data!.expand(
(channel) => [channel.r, channel.g, channel.b]).map(
(value) => value.toDouble()).toList();
Float32List float32Array = Float32List.fromList(flattenedList);
int channels = 3;
int height = HEIGHT;
int width = WIDTH;
Float32List reshapedArray = Float32List(1 * height * width * channels);
for (int c = 0; c < channels; c++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int index = c * height * width + h * width + w;
reshapedArray[index] = (float32Array[c * height * width + h * width + w]-127.5)/127.5;
}
}
}
// return reshapedArray.reshape([1,112,112,3]);
return reshapedArray.reshape([1,160,160,3]);
}
Recognition recognize(img.Image image, Rect location) {
//TODO crop face from image resize it and convert it to float array
var input = imageToArray(image);
debugPrint(input.shape.toString());
//TODO output array
// List output = List.filled(1*192, 0).reshape([1,192]);
List output = List.filled(1*512, 0).reshape([1,512]);
//TODO performs inference
final runs = DateTime.now().millisecondsSinceEpoch;
interpreter.run(input, output);
final run = DateTime.now().millisecondsSinceEpoch - runs;
debugPrint('Time to run inference: $run ms$output');
//TODO convert dynamic list to double list
List<double> outputArray = output.first.cast<double>();
//TODO looks for the nearest embeeding in the database and returns the pair
Pair pair = findNearest(outputArray);
debugPrint("distance= ${pair.distance}");
return Recognition(pair.name,location,outputArray,pair.distance);
}
List<double> getEmbedding(img.Image image, Rect location) {
//TODO crop face from image resize it and convert it to float array
var input = imageToArray(image);
debugPrint(input.shape.toString());
//TODO output array
// List output = List.filled(1*192, 0).reshape([1,192]);
List output = List.filled(1*512, 0).reshape([1,512]);
//TODO performs inference
final runs = DateTime.now().millisecondsSinceEpoch;
interpreter.run(input, output);
final run = DateTime.now().millisecondsSinceEpoch - runs;
debugPrint('Time to run inference: $run ms$output');
//TODO convert dynamic list to double list
return output.first.cast<double>();
}
//TODO looks for the nearest embeeding in the database and returns the pair which contain information of registered face with which face is most similar
findNearest(List<double> emb){
Pair pair = Pair(" ليست ${UserData.fullName} ", -5);
// for (MapEntry<String, Recognition> item in registered.entries) {
// final String name = item.key;
List<double> knownEmb = AppConstants.embedding ; //item.value.embeddings;
double distance = 0;
for (int i = 0; i < emb.length; i++) {
double diff = emb[i] -
knownEmb[i];
distance += diff*diff;
}
distance = sqrt(distance);
if (pair.distance == -5 || distance < pair.distance) {
pair.distance = distance;
if( distance < 1) pair.name = UserData.fullName;
}
// }
return pair;
}
void close() {
interpreter.close();
}
}
class Pair{
String name;
double distance;
Pair(this.name,this.distance);
}
I can’t trak the error because it’s on the release version I don’t know really what to do.
I tried to many solutions but still the same.
I don’t know what is the issue here.