Flutter人脸识别插件xbr_baidu_face的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter人脸识别插件xbr_baidu_face的使用

介绍

XBR 百度人脸采集封装插件

使用说明

  1. 前往百度智能云官网申请 license 文件(需配置 APP 签名,.jks 生成和 signing 自行百度)。
  2. Android:在 android-main 下面新建 assets 文件夹,放入 idl-license.face-android 文件。 IOS:在 ios-Runner 下面放入 idl-license.face-ios 文件。
  3. 初始化百度 FACE 后即可开始采集。

更新说明

  1. 安卓端 FACE-SDK 升级到:4.1.5,在 FlutterBdfaceCollect 基础上完成 Android 部分机型的修复,如小米9-pro等。
  2. 基于 SDK 新特性,重写了大量 Android 端代码。

使用

// 初始化:
void initBdFace() {
  if (Platform.isAndroid){
    FlutterBdfaceCollect.instance.init("driver-face-face-android");
  }else{
    FlutterBdfaceCollect.instance.init("iosLicenseId");
  }
}

// 开始采集:
Future<void> liveDetect() async {
  FaceConfig config = FaceConfig(livenessTypes: Set.from(LivenessType.all.sublist(1, 4)));
  CollectResult res = await FlutterBdfaceCollect.instance.collect(config);
  if(res.error.isNotEmpty){
    print(res.error);
    return;
  }
  print(res.imageSrcBase64);
}

注意事项

  1. 采集前需要配置相机权限,并使用动态权限。
  2. 如果日志中出现异常:java.io.FileNotFoundException: idl-license.face-android,说明没有 license 文件,或 license 文件放错位置。

参与贡献

  1. XBR 团队

示例代码

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:xbr_baidu_face/flutter_bdface_collect.dart';
import 'package:xbr_baidu_face/model.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    super.initState();
    initBdFace();
  }

  /// 初始化百度 FACE
  void initBdFace() {
    if (Platform.isAndroid){
      FlutterBdfaceCollect.instance.init("driver-face-face-android");
    }else{
      FlutterBdfaceCollect.instance.init("iosLicenseId");
    }
  }

  /// 开始采集
  Future<void> liveDetect() async {
    FaceConfig config = FaceConfig(livenessTypes: Set.from(LivenessType.all.sublist(1, 4)));
    CollectResult res = await FlutterBdfaceCollect.instance.collect(config);
    debugPrint('采集错误结果:${res.error.isNotEmpty} 内容:${res.error}');
    debugPrint('采集原图 imageCropBase64:${res.imageSrcBase64.isNotEmpty}');
    debugPrint('采集抠图 imageSrcBase64:${res.imageCropBase64.isNotEmpty}');
    if(res.error.isNotEmpty){
      return;
    }
    setState(() {
      _bytes = base64Decode(res.imageCropBase64);
    });
  }
  
  Uint8List? _bytes;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("百度人脸采集调试"),
        ),
        body: Container(
          padding: const EdgeInsets.all(30),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('欢迎使用小镖人百度人脸采集系统', style: style1),
              const SizedBox(height: 16),
              const Text('1:创建 JKS 秘钥文件,完成 APP 签名,自行百度查看方法,前往百度智能云官网申请 license 文件', style: style2),
              const SizedBox(height: 10),
              const Text('2-1:在 android-main 下面新建 assets 文件夹,放入 idl-license.face-android 文件 ', style: style2),
              const SizedBox(height: 10),
              const Text('2-2:在 ios-Runner 下面放入 idl-license.face-ios 文件 ', style: style2),
              const SizedBox(height: 10),
              const Text('3:初始化百度 FACE,点击第 4 步即可开始采集', style: style2),
              const SizedBox(height: 10),
              OutlinedButton(
                onPressed: () {liveDetect();},
                child: const Text("4:点击开始采集", style: style1),
              ),
              if (_bytes != null)
                SizedBox(
                  width: 150,
                  height: 150,
                  child: Image.memory(_bytes!, fit: BoxFit.cover),
                ),
              const Text('注意:example 未配置动态权限,测试时需要手动赋予权限', style: style2),
              const Text("如果日志中出现异常:java.io.FileNotFoundException: idl-license.face-android,说明没有 license 文件,或 license 文件放错位置")
            ],
          ),
        ),
      ),
    );
  }
}

const TextStyle style1 = TextStyle(fontWeight: FontWeight.bold, fontSize: 24);
const TextStyle style2 = TextStyle(fontWeight: FontWeight.bold, fontSize: 16);

更多关于Flutter人脸识别插件xbr_baidu_face的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter人脸识别插件xbr_baidu_face的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用xbr_baidu_face插件进行人脸识别的示例代码。这个插件封装了百度人脸识别API的功能。在使用之前,请确保你已经按照插件的官方文档完成了必要的配置,比如申请百度AI的API Key和Secret Key,并在你的Flutter项目中添加了依赖。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加xbr_baidu_face依赖:

dependencies:
  flutter:
    sdk: flutter
  xbr_baidu_face: ^最新版本号 # 替换为当前最新版本号

然后运行flutter pub get来安装依赖。

2. 配置百度AI的API Key和Secret Key

android/app/src/main/AndroidManifest.xmlios/Runner/Info.plist中配置你的百度AI API Key和Secret Key(具体配置方式请参考插件的官方文档)。

3. 初始化插件并进行人脸识别

在你的Dart代码中,你可以按照以下步骤初始化插件并进行人脸识别:

import 'package:flutter/material.dart';
import 'package:xbr_baidu_face/xbr_baidu_face.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final XbrBaiduFace _baiduFace = XbrBaiduFace();

  @override
  void initState() {
    super.initState();
    // 初始化插件(可选,根据插件文档决定是否需要)
    _baiduFace.init();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter 人脸识别示例'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 这里假设你有一个图像文件路径或者Uint8List数据
              // 例如,从相机或图库中选择了一张图片
              String imagePath = "path/to/your/image.jpg"; // 替换为你的图片路径
              // 或者使用Uint8List数据
              // Uint8List imageData = ...; // 你的图像数据

              try {
                // 使用图像路径进行人脸识别
                // 注意:这里只是示例,实际使用中需要处理错误和结果
                var result = await _baiduFace.detectFace(imagePath: imagePath);
                print("人脸识别结果: $result");

                // 如果需要使用Uint8List数据,可以使用下面的方法
                // var result = await _baiduFace.detectFace(imageData: imageData);
                // print("人脸识别结果: $result");

                // 根据result处理人脸识别结果,比如显示人脸框、关键点等
              } catch (e) {
                print("人脸识别失败: $e");
              }
            },
            child: Text('进行人脸识别'),
          ),
        ),
      ),
    );
  }
}

注意事项

  1. 权限处理:确保你的应用有读取存储和相机权限(如果图片来自相机或图库)。
  2. 错误处理:在实际应用中,应该添加更多的错误处理逻辑,比如网络错误、API调用限制等。
  3. API调用频率:注意百度AI API的调用频率限制,避免频繁调用导致API被封禁。
  4. UI更新:如果需要在UI上展示人脸识别结果,比如绘制人脸框或关键点,你可能需要使用CustomPaint等Widget来绘制。

这个示例代码展示了如何在Flutter项目中使用xbr_baidu_face插件进行基本的人脸识别。根据你的具体需求,你可能需要进一步定制和扩展这个示例。

回到顶部