在颤动中识别人脸

问题描述 投票:0回答:1

我正在制作应用程序来使用 [google ml 套件][1] 来检测和识别检测到的面部。我正在使用 sqflite 包在本地存储人员数据。检测到面部,所以我想存储检测到的面部并识别检测到的人脸。我已经实现了检测功能,所以我想存储并识别人脸。接受任何建议。

class Person {
  Person(
      {required this.id,
      required this.name,
      required this.template,
      required this.image});
  int id;
  String name;
  ByteData template;
  ByteData image;
  factory Person.fromJson(Map<String, dynamic> json) => Person(
      id: json['id'],
      name: json['name'],
      template: json['template'],
      image: json['image']);
  Map<String, dynamic> toJson() =>
      {"id": id, "name": name, "template": template, "image": image};
}

数据库控制器

import 'package:flutter_firebase/personModel.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io' as io;
import 'package:path/path.dart';

class DbController {
  static Database? database;
  String tableName = "person";
  Future<Database?> get db async {
    if (database != null) {
      return database;
    }
    database = await initDatabase();
    return database;
  }

  Future<Database> initDatabase() async {
    io.Directory directory = await getApplicationDocumentsDirectory();
    String path = join(directory.path, "myDb.db");
    Database database = await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) {
     String table =
    "create table $tableName(id integer primary key auto increment,name text,template blob,image blob,faceEmbeddings blob)";

        db.execute(table);
      },
    );
    return database;
  }

  Future<bool> insertPerson(Person person) async {
    try {
      var dbClient = await db;
      dbClient!.insert(tableName, person.toJson()).then((value) {
        return true;
      });
    } catch (e) {
      print("e:$e");
    }
    return false;
  }

  Future<List<Person>> getPerson() async {
    var dbClient = await db;
    if (dbClient == null) return [];
    final List<Map<String, Object?>> result = await dbClient.query(tableName);
    return result.map((e) => Person.fromJson(e)).toList();
  }
}

图库查看页面

import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get_connect/http/src/utils/utils.dart';
import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:ui' as ui;

class GalleryView extends StatefulWidget {
  const GalleryView({super.key});

  @override
  State<GalleryView> createState() => _GalleryViewState();
}

class _GalleryViewState extends State<GalleryView> {
  File? _image;
  ui.Image? iimage;
  List<Face> faceses = [];
  pickImage() async {
    try {
      final pickedImage =
          await ImagePicker().pickImage(source: ImageSource.gallery);
      if (pickedImage != null) {
        _image = File(pickedImage.path);

        await _loadImage(_image!);
        await detectFace();
        setState(() {});
      } else {
        print("no image is picked");
      }
    } catch (e) {
      print("Exception $e");
    }
  }

  _loadImage(File file) async {
    final data = await file.readAsBytes();
    await decodeImageFromList(data).then((value) => iimage = value);
  }

  detectFace() async {
    InputImage inputImage = InputImage.fromFile(_image!);
    final faceDetector = GoogleMlKit.vision.faceDetector(FaceDetectorOptions(
        performanceMode: FaceDetectorMode.accurate,
        enableLandmarks: true, // enable landmark
        enableContours: true,
        enableTracking: true,
        enableClassification: true));
    faceses = await faceDetector.processImage(inputImage);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _image != null
                ? Container(
                    child: Image.file(
                      File(_image!.path),
                      fit: BoxFit.cover,
                    ),
                  )
                : Container(
                    child: const Icon(
                      Icons.image,
                      size: 100,
                    ),
                  ),
            faceses.isNotEmpty
                ? FittedBox(
                    child: SizedBox(
                      width: iimage?.width.toDouble(),
                      height: iimage?.height.toDouble(),
                      child: CustomPaint(
                        painter: FacePainter(iimage!, faceses),
                      ),
                    ),
                  )
                : Container(),
            faceses.isNotEmpty
                ? Text(
                    "Number of detected faces is ${faceses.length.toString()}")
                : const Text("no face detected"),
            TextButton(
                onPressed: () {
                  pickImage();
                },
                child: const Text("Pick Image and detect face")),
          ],
        ),
      )),
    );
  }
}

class FacePainter extends CustomPainter {
  ui.Image image;
  List<Face> faces;
  List<Rect> boundingBoxes = [];
  FacePainter(this.image, this.faces) {
    for (var face in faces) {
      boundingBoxes.add(face.boundingBox);
     
    }
  }

  @override
  void paint(ui.Canvas canvas, ui.Size size) {
    final Paint boundingBoxPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0
      ..color = Colors.blue;

 
    canvas.drawImage(image, Offset.zero, Paint()); //draw rectangle around face
//draw facecontour
    for (var i = 0; i < faces.length; i++) {
      canvas.drawRect(boundingBoxes[i], boundingBoxPaint);
    }
  }

  @override
  bool shouldRepaint(FacePainter oldDelegate) {
    return image != oldDelegate.image || faces != oldDelegate.faces;
  }
}


  [1]: https://pub.dev/packages/google_ml_kit
flutter face-recognition google-mlkit
1个回答
-1
投票

请参考这个示例和当前使用的软件包:

  • google_ml_kit
  • tflite_flutter

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.