Flutter人脸活体检测插件biopassid_face_liveness_sdk的使用

Flutter人脸活体检测插件biopassid_face_liveness_sdk的使用

BioPass ID

BioPass ID Face Liveness SDK Flutter

Flutter Pub Instagram BioPass ID Contact us

快速开始指南前提条件安装如何使用许可证密钥获取人脸捕获FaceLivenessConfig更改字体家族更改图标其他更新日志支持

快速开始指南

首先,您需要一个许可证密钥才能使用biopassid_face_liveness_sdk。要获取您的许可证密钥,请通过我们的网站 BioPass ID 联系我们。

检查我们的 官方文档 以获取更多有关BioPass ID的信息。

前提条件

Android iOS
支持 SDK 24+ iOS 15+
- 一个带有摄像头的设备
- 许可证密钥
- 需要互联网连接来验证许可证

安装

首先,在您的 pubspec.yaml 文件中添加 biopassid_face_liveness_sdk 作为依赖项。

Android

在您的 android/app/build.gradle 文件中将最低 Android SDK 版本更改为 24(或更高)。

minSdkVersion 24

iOS

需要 iOS 15.0 或更高版本。

ios/Info.plist 中添加以下内容:

<key>NSCameraUsageDescription</key>
<string>Your camera usage description</string>

然后进入项目 ios 文件夹并运行 pod install

# 进入 ios 文件夹
$ cd ios

# 安装依赖项
$ pod install

隐私清单文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>NSPrivacyCollectedDataTypes</key>
	<array>
		<dict>
			<key>NSPrivacyCollectedDataType</key>
			<string>NSPrivacyCollectedDataTypeOtherUserContent</string>
			<key>NSPrivacyCollectedDataTypeLinked</key>
			<false/>
			<key>NSPrivacyCollectedDataTypeTracking</key>
			<false/>
			<key>NSPrivacyCollectedDataTypePurposes</key>
			<array>
				<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
			</array>
		</dict>
		<dict>
			<key>NSPrivacyCollectedDataType</key>
			<string>NSPrivacyCollectedDataTypeDeviceID</string>
			<key>NSPrivacyCollectedDataTypeLinked</key>
			<false/>
			<key>NSPrivacyCollectedDataTypeTracking</key>
			<false/>
			<key>NSPrivacyCollectedDataTypePurposes</key>
			<array>
				<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
			</array>
		</dict>
	</array>
	<key>NSPrivacyTracking</key>
	<false/>
	<key>NSPrivacyAccessedAPITypes</key>
	<array>
		<dict>
			<key>NSPrivacyAccessedAPITypeReasons</key>
			<array>
				<string>CA92.1</string>
			</array>
			<key>NSPrivacyAccessedAPIType</key>
			<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
		</dict>
	</array>
</dict>
</plist>

如何使用

基本示例

要在您的 Flutter 项目中调用 Face Liveness,只需按如下步骤操作:

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Face Liveness Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late FaceLivenessController controller;

  @override
  void initState() {
    super.initState();
    final config = FaceLivenessConfig(licenseKey: 'your-license-key');
    controller = FaceLivenessController(
      config: config,
      onFaceCapture: (image, faceAttributes) {
        print('onFaceCapture: ${image.first}');
        print('onFaceCapture: $faceAttributes');
      },
      onFaceDetected: (faceAttributes) {
        print('onFaceDetected: $faceAttributes');
      },
      debug: false,
    );
  }

  void takeFace() async {
    await controller.takeFace();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Face Liveness Demo')),
      body: Center(
        child: ElevatedButton(
          onPressed: takeFace,
          child: const Text('Capture Face'),
        ),
      ),
    );
  }
}

使用 http 包调用 BioPass ID API 的示例

在这个示例中,我们使用了 Liveness 来自 Multibiometrics 计划

首先,添加 http 包。在 pubspec.yaml 文件的依赖部分添加它。您可以在 pub.dev 上找到最新版本的 http 包。

dependencies:
  http: <latest_version>

此外,在您的 AndroidManifest.xml 文件中添加互联网权限。

<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />

在这里,您需要一个 API 密钥才能向 BioPass ID API 发送请求。要获取您的 API 密钥,请通过我们的网站 BioPass ID 联系我们。

import 'dart:convert';

import 'package:biopassid_face_liveness_sdk/biopassid_face_liveness_sdk.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Face Liveness Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late FaceLivenessController controller;

  @override
  void initState() {
    super.initState();
    final config = FaceLivenessConfig(licenseKey: 'your-license-key');
    controller = FaceLivenessController(
      config: config,
      onFaceCapture: (image, faceAttributes) async {
        // 编码图像为 base64 字符串
        final imageBase64 = base64Encode(image);

        // 创建 URL
        final url = Uri.https('api.biopassid.com', 'multibiometrics/v2/liveness');

        // 创建包含 API 密钥的头部
        final headers = {
          'Content-Type': 'application/json',
          'Ocp-Apim-Subscription-Key': 'your-api-key'
        };

        // 创建 JSON 请求体
        final body = json.encode({
          'Spoof': {'Image': imageBase64}
        });

        // 执行向 BioPass ID API 的请求
        final response = await http.post(
          url,
          headers: headers,
          body: body,
        );

        // 处理 API 响应
        print('Response status: ${response.statusCode}');
        print('Response body: ${response.body}');
      },
      onFaceDetected: (faceAttributes) {
        print('onFaceDetected: $faceAttributes');
      },
      debug: false,
    );
  }

  void takeFace() async {
    await controller.takeFace();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Face Liveness Demo')),
      body: Center(
        child: ElevatedButton(
          onPressed: takeFace,
          child: const Text('Capture Face'),
        ),
      ),
    );
  }
}

许可证密钥

首先,您需要一个许可证密钥才能使用 biopassid_face_liveness_sdk。要获取您的许可证密钥,请通过我们的网站 BioPass ID 联系我们。

要使用 biopassid_face_liveness_sdk,您需要一个许可证密钥。设置所需的许可证密钥非常简单,只需设置另一个属性即可。只需这样做:

final config = FaceLivenessConfig(licenseKey: 'your-license-key');

获取人脸捕获

您可以传递一个回调函数来接收捕获的图像。您可以按照此示例编写自己的回调:

final config = FaceLivenessConfig(licenseKey: 'your-license-key');
final controller = FaceLivenessController(
    config: config,
    onFaceCapture: (image, faceAttributes) {
      print('onFaceCapture: ${image.first}');
      print('onFaceCapture: $faceAttributes');
    },
    onFaceDetected: (faceAttributes) {
      print('onFaceDetected: $faceAttributes');
    },
    debug: false,
);
await controller.takeFace();

LivenessFaceAttributes

名称 类型 描述
faceProp double 面部在图像中所占面积的比例,以百分比表示
faceWidth int 面部宽度,以像素为单位
faceHeight int 面部高度,以像素为单位
ied int 左眼和右眼之间的距离,以像素为单位
bbox Rect 面部边界框
rollAngle double 头部的欧拉角 X。指示面部绕着指向图像外的轴旋转
pitchAngle double 头部的欧拉角 X。指示面部绕着图像水平轴旋转
yawAngle double 头部的欧拉角 Y。指示面部绕着图像垂直轴旋转
leftEyeOpenProbability // Android only double? 面部左眼张开的概率,以百分比表示
rightEyeOpenProbability // Android only double? 面部右眼张开的概率,以百分比表示
smilingProbability // Android only double? 面部微笑的概率,以百分比表示
averageLightIntensity double 图像中像素的平均强度

FaceLivenessConfig

您还可以在应用程序中使用预构建的配置,以便您可以自动开始使用多个更适合您的应用的服务和功能。您可以实例化每个配置并使用其默认属性,或者如果您愿意,可以更改所有可用的配置。目前支持的类型有:

FaceLivenessConfig

名称 类型 默认值
licenseKey String ‘’
resolutionPreset FaceLivenessResolutionPreset FaceLivenessResolutionPreset.veryHigh
fontFamily String ‘facelivenesssdk_opensans_bold’
faceDetection FaceLivenessDetectionOptions
mask FaceLivenessMaskOptions
titleText FaceLivenessTextOptions
loadingText FaceLivenessTextOptions
helpText FaceLivenessTextOptions
feedbackText FaceLivenessFeedbackTextOptions
backButton FaceLivenessButtonOptions

默认配置:

final defaultConfig = FaceLivenessConfig(
  licenseKey: '',
  resolutionPreset: FaceLivenessResolutionPreset.veryHigh,
  fontFamily: 'facelivenesssdk_ic_close',
  faceDetection: FaceLivenessDetectionOptions(
    timeToCapture: 3000,
    maxFaceDetectionTime: 60000,
    minFaceProp: 0.1,
    maxFaceProp: 0.4,
    minFaceWidth: 150,
    minFaceHeight: 150,
    ied: 90,
    bboxPad: 20,
    faceDetectionThresh: 0.5,
    rollThresh: 4.0,
    pitchThresh: 4.0,
    yawThresh: 4.0,
    closedEyesThresh: 0.7, // Android only
    smilingThresh: 0.7, // Android only
    tooDarkThresh: 50,
    tooLightThresh: 170,
    faceCentralizationThresh: 0.05,
  ),
  mask: FaceLivenessMaskOptions(
    enabled: true,
    backgroundColor: const Color(0xCC000000),
    frameColor: const Color(0xFFFFFFFF),
    frameEnabledColor: const Color(0xFF16AC81),
    frameErrorColor: const Color(0xFFE25353),
  ),
  titleText: FaceLivenessTextOptions(
    enabled: true,
    content: 'Capturing Face',
    textColor: const Color(0xFFFFFFFF),
    textSize: 20,
  ),
  loadingText: FaceLivenessTextOptions(
    enabled: true,
    content: 'Processing...',
    textColor: const Color(0xFFFFFFFF),
    textSize: 14,
  ),
  helpText: FaceLivenessTextOptions(
    enabled: true,
    content: 'Fit your face into the shape below',
    textColor: const Color(0xFFFFFFFF),
    textSize: 14,
  ),
  feedbackText: FaceLivenessFeedbackTextOptions(
    enabled: true,
    messages: FaceLivenessFeedbackTextMessages(
      noDetection: 'No faces detected',
      multipleFaces: 'Multiple faces detected',
      faceCentered: 'Face centered. Do not move',
      tooClose: 'Turn your face away',
      tooFar: 'Bring your face closer',
      tooLeft: 'Move your face to the right',
      tooRight: 'Move your face to the left',
      tooUp: 'Move your face down',
      tooDown: 'Move your face up',
      invalidIED: 'Invalid inter-eye distance',
      faceAngleMisaligned: 'Misaligned face angle',
      closedEyes: 'Open your eyes', // Android only
      smiling: 'Do not smile', // Android only
      tooDark: 'Too dark',
      tooLight: 'Too light',
    ),
    textColor: const Color(0xFFFFFFFF),
    textSize: 14,
  ),
  backButton: FaceLivenessButtonOptions(
    enabled: true,
    backgroundColor: const Color(0x00000000),
    buttonPadding: 0,
    buttonSize: const Size(56, 56),
    iconOptions: FaceLivenessIconOptions(
      enabled: true,
      iconFile: 'facelivenesssdk_ic_close',
      iconColor: const Color(0xFFFFFFFF),
      iconSize: const Size(32, 32),
    ),
    labelOptions: FaceLivenessTextOptions(
      enabled: false,
      content: 'Back',
      textColor: const Color(0xFFFFFFFF),
      textSize: 14,
    ),
  ),
);

FaceLivenessDetectionOptions

名称 类型 默认值 描述
timeToCapture int 3000 自动捕获所需的时间,以毫秒为单位
maxFaceDetectionTime int 60000 最大面部检测尝试时间,以毫秒为单位
minFaceProp double 0.1 面部在图像中所占面积的最小比例,以百分比表示
maxFaceProp double 0.4 面部在图像中所占面积的最大比例,以百分比表示
minFaceWidth int 150 最小面部宽度,以像素为单位
minFaceHeight int 150 最小面部高度,以像素为单位
ied int 90 最小左眼和右眼之间的距离,以像素为单位
bboxPad int 20 面部边界框填充到图像边缘的像素数量
faceDetectionThresh double 0.5 检测的有效性的最低信任分数。必须是一个介于 0 和 1 之间的数字,0.1 表示较低的面部检测信任度,0.9 表示较高的信任度
rollThresh double 4.0 头部的欧拉角 X。指示面部绕着指向图像外的轴旋转
pitchThresh double 4.0 头部的欧拉角 X。指示面部绕着图像水平轴旋转
yawThresh double 4.0 头部的欧拉角 Y。指示面部绕着图像垂直轴旋转
closedEyesThresh // Android only double 0.7 左眼和右眼闭合的最小概率阈值,以百分比表示。小于 0.7 表示眼睛可能闭合
smilingThresh // Android only double 0.7 面部微笑的最小概率阈值,以百分比表示。0.7 或以上表示一个人很可能在笑
tooDarkThresh int 50 图像中像素平均强度的最小阈值
tooLightThresh int 170 图像中像素平均强度的最大阈值
faceCentralizationThresh double 0.05 面部居中的阈值,以百分比表示

FaceLivenessMaskOptions

名称 类型 默认值
enabled bool true
backgroundColor Color Color(0xCC000000)
frameColor Color Color(0xFFFFFFFF)
frameEnabledColor Color Color(0xFF16AC81)
frameErrorColor Color Color(0xFFE25353)

FaceLivenessFeedbackTextOptions

名称 类型 默认值
enabled bool true
messages FaceLivenessFeedbackTextMessages FaceLivenessFeedbackTextMessages()
textColor Color Color(0xFFFFFFFF)
textSize int 14

FaceLivenessFeedbackTextMessages

名称 类型 默认值
noDetection String ‘No faces detected’
multipleFaces String ‘Multiple faces detected’
faceCentered String ‘Face centered. Do not move’
tooClose String ‘Turn your face away’
tooFar String ‘Bring your face closer’
tooLeft String ‘Move your face to the right’
tooRight String ‘Move your face to the left’
tooUp String ‘Move your face down’
tooDown String ‘Move your face up’
invalidIED String ‘Invalid inter-eye distance’
faceAngleMisaligned String ‘Misaligned face angle’
closedEyes // Android only String ‘Open your eyes’
smiling // Android only String ‘Do not smile’
tooDark String ‘Too dark’
tooLight String ‘Too light’

FaceLivenessButtonOptions

名称 类型 默认值
enabled bool true
backgroundColor Color Color(0xFFFFFFFF)
buttonPadding int 0
buttonSize Size Size(56, 56)
iconOptions FaceLivenessIconOptions
labelOptions FaceLivenessTextOptions

FaceLivenessIconOptions

名称 类型 默认值
enabled bool true
iconFile String ‘facelivenesssdk_ic_close’
iconColor Color Color(0xFF323232)
iconSize Size Size(32, 32)

FaceLivenessTextOptions

名称 类型 默认值
enabled bool true
content String ‘’
textColor Color Color(0xFF323232)
textSize int 14

FaceLivenessResolutionPreset (枚举)

名称 分辨率
FaceLivenessResolutionPreset.high 720p (1280x720)
FaceLivenessResolutionPreset.veryHigh 1080p (1920x1080)

如何更改字体家族

在 Android 端

您可以使用默认字体家族或设置自己的字体家族。要设置字体家族,请在 android/app/src/main/res 目录下创建一个名为 font 的文件夹。下载您想要的字体,并将其粘贴到字体文件夹中。所有字体文件名必须仅包含:小写 a-z、0-9 或下划线。结构应该类似于下面的样子。

设置字体

在 iOS 端

要将字体文件添加到您的 Xcode 项目中:

  1. 在 Xcode 中,选择项目导航器。
  2. 从 Finder 窗口中拖动您的字体到您的项目中。这会将字体复制到您的项目中。
  3. 选择字体或包含字体的文件夹,并确认文件显示它们的目标成员资格已选中您的应用程序的目标。

添加字体

然后,将 “Fonts provided by application” 键添加到您的应用程序的 Info.plist 文件中。对于键的值,提供一个包含任何添加字体文件相对路径的字符串数组。

在下面的示例中,字体文件位于 fonts 目录中,因此您在 Info.plist 文件中使用 fonts/roboto_mono_bold_italic.ttf 作为字符串值。

字体路径

在 Dart 端

最后,只需在初始化 FaceLivenessConfig 时传递字体文件名即可。

final config = FaceLivenessConfig(
  licenseKey: 'your-license-key',
  fontFamily: 'roboto_mono_bold_italic',
);

如何更改图标

在 Android 端

您可以使用默认图标或定义自己的图标。要设置图标,下载您想要的图标并将其粘贴到 android/app/src/main/res 下的 drawable 文件夹中。所有图标文件名必须仅包含:小写 a-z、0-9 或下划线。结构应该类似于下面的样子。

设置图标

在 iOS 端

要将图标文件添加到您的 Xcode 项目中:

  1. 在项目导航器中,选择一个资产目录:一个扩展名为 .xcassets 的文件。
  2. 将图像从 Finder 拖放到轮廓视图中。一个新的图像集出现在轮廓视图中,而图像资产出现在详细区域中的一个框中。

添加图标

在 Dart 端

最后,只需在初始化 FaceLivenessConfig 时传递图标文件名即可。

final config = FaceLivenessConfig(licenseKey: 'your-license-key');
// 更改后退按钮图标
config.backButton.iconOptions.iconFile = 'ic_baseline_camera';

更多关于Flutter人脸活体检测插件biopassid_face_liveness_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


biopassid_face_liveness_sdk 是一个用于 Flutter 应用的人脸活体检测插件。它可以帮助开发者轻松集成人脸活体检测功能,以确保用户在进行身份验证时是真实的、活体的人脸。

以下是如何在 Flutter 项目中使用 biopassid_face_liveness_sdk 的步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 biopassid_face_liveness_sdk 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  biopassid_face_liveness_sdk: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化 SDK

在使用 SDK 之前,你需要对其进行初始化。通常,你需要在应用的入口处(如 main.dart 文件)进行初始化:

import 'package:biopassid_face_liveness_sdk/biopassid_face_liveness_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 SDK
  await BiopassidFaceLivenessSdk.initialize(
    apiKey: 'YOUR_API_KEY',  // 替换为你的 API Key
    apiSecret: 'YOUR_API_SECRET',  // 替换为你的 API Secret
  );
  
  runApp(MyApp());
}

3. 启动活体检测

在需要启动活体检测的地方,你可以调用 startLivenessDetection 方法:

import 'package:biopassid_face_liveness_sdk/biopassid_face_liveness_sdk.dart';

void startLivenessDetection() async {
  try {
    // 启动活体检测
    final result = await BiopassidFaceLivenessSdk.startLivenessDetection();
    
    // 处理检测结果
    if (result.isLive) {
      print('活体检测通过');
      print('检测结果: ${result.image}');  // 获取检测后的图像
    } else {
      print('活体检测未通过');
    }
  } catch (e) {
    print('活体检测失败: $e');
  }
}
回到顶部