Flutter人脸识别插件sr_arc_face的使用

Flutter人脸识别插件sr_arc_face的使用

本项目练手项目使用的是虹软免费版本3.0的sdk。

使用的时候请及时替换sdk免费版本一年会自动过期。


配置pubspec.yaml

dependencies:
  sr_arc_face: https://github.com/UseZwb/sr_arc_face.git

引入

import 'package:sr_arc_face/arcFace_camera_view.dart';
import 'package:sr_arc_face/sr_arc_face.dart';

使用

import 'package:flutter/material.dart';

import 'package:sr_arc_face/arcFace_camera_view.dart';
import 'package:sr_arc_face/sr_arc_face.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  ArcFaceController arcFaceController = ArcFaceController();
  bool isActive = false;
  String userName = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      init();
    });
  }

  onCreated() {
    arcFaceController.faceDetectStreamListen((data) {
      print('------------res------------');
      print(data);
      print('------------res------------');
      setState(() {
        userName = data;
      });
    });
  }

  init() async {
    try {
      bool result = await SrArcFace.activeOnLine(
          '', // APP_ID
          '', // SDK_KEY
          rootPath: ''); // 可不传默认为 getExternalStorageDirectory + '/arcFace'
      print(result);
      if (result)
        setState(() {
          isActive = result;
        });
    } catch (e) {
      print(e);
    }

    /// 获取激活文件信息
    final activeInfo = await SrArcFace.getActiveFileInfo();
    print(activeInfo.toJson());

    /// 获取版本信息
    final versionInfo = await SrArcFace.getSdkVersion();
    print(versionInfo.toJson());
    // 设置视频检测角度
    SrArcFace.setFaceDetectDegree(FaceDetectOrientPriorityEnum.ASF_OP_ALL_OUT);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: 500,
                height: 500,
                child: isActive
                    ? ArcFaceCameraView(
                        controller: arcFaceController,
                        showRectView: true,
                        similarity: 0.75,
                        livingDetect: true,
                        maxDetectNum: 10,
                        onCreated: onCreated,
                      )
                    : Container(),
              ),
              TextButton(
                onPressed: () {
                  if (!arcFaceController.isCreate) {
                    return print('未创建');
                  }
                  // root 默认为 getExternalStorageDirectory
                  print('请把人脸图片.jpg 放入传入的 rootPath + "/registed/images/" 文件夹中');
                  print('默认为 rootPath + "/arcFace/registed/images/"');
                  arcFaceController.register();
                },
                child: Text('注册人脸'),
              ),
              Text(userName)
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


sr_arc_face 是一个用于 Flutter 的人脸识别插件,它基于 ArcSoft 的人脸识别技术。这个插件可以帮助开发者在 Flutter 应用中实现人脸检测、人脸识别、人脸特征提取等功能。以下是如何在 Flutter 项目中使用 sr_arc_face 插件的基本步骤。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  sr_arc_face: ^1.0.0  # 请使用最新的版本号

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

2. 初始化插件

在使用插件之前,你需要先初始化它。通常,你可以在 main.dart 文件中进行初始化。

import 'package:sr_arc_face/sr_arc_face.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 ArcFace
  await SrArcFace.initArcFace();
  
  runApp(MyApp());
}

3. 使用插件进行人脸检测

你可以使用 SrArcFace 提供的 API 来进行人脸检测。以下是一个简单的例子,展示如何在图像中检测人脸。

import 'package:flutter/material.dart';
import 'package:sr_arc_face/sr_arc_face.dart';
import 'dart:ui' as ui;

class FaceDetectionPage extends StatefulWidget {
  @override
  _FaceDetectionPageState createState() => _FaceDetectionPageState();
}

class _FaceDetectionPageState extends State<FaceDetectionPage> {
  List<FaceInfo> faces = [];

  Future<void> detectFaces() async {
    // 加载图片
    ByteData data = await rootBundle.load('assets/face_image.jpg');
    ui.Image image = await decodeImageFromList(data.buffer.asUint8List());

    // 检测人脸
    faces = await SrArcFace.detectFaces(image);

    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    detectFaces();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Face Detection'),
      ),
      body: Center(
        child: faces.isEmpty
            ? CircularProgressIndicator()
            : Text('Detected ${faces.length} faces'),
      ),
    );
  }
}

4. 人脸特征提取

你还可以使用 SrArcFace 来提取人脸特征,以便进行人脸识别。

Future<void> extractFaceFeature() async {
  if (faces.isNotEmpty) {
    FaceInfo face = faces.first;
    FaceFeature feature = await SrArcFace.extractFaceFeature(face);
    print('Face feature: ${feature.feature}');
  }
}

5. 人脸比对

你可以使用提取的人脸特征来进行人脸比对。

Future<void> compareFaces() async {
  if (faces.length >= 2) {
    FaceFeature feature1 = await SrArcFace.extractFaceFeature(faces[0]);
    FaceFeature feature2 = await SrArcFace.extractFaceFeature(faces[1]);

    double similarity = await SrArcFace.compareFaces(feature1, feature2);
    print('Face similarity: $similarity');
  }
}

6. 释放资源

在应用退出或不再需要使用人脸识别功能时,记得释放资源。

@override
void dispose() {
  SrArcFace.releaseArcFace();
  super.dispose();
}

7. 处理权限

在使用人脸识别功能时,确保你已经获取了必要的权限(如相机权限)。你可以在 AndroidManifest.xmlInfo.plist 中添加相应的权限声明,并在运行时请求权限。

8. 处理错误

在实际使用中,可能会遇到各种错误(如初始化失败、人脸检测失败等)。你可以使用 try-catch 块来捕获和处理这些错误。

try {
  await SrArcFace.initArcFace();
} catch (e) {
  print('Failed to initialize ArcFace: $e');
}
回到顶部