Flutter人脸识别插件apple_vision_selfie的使用

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

Flutter人脸识别插件apple_vision_selfie的使用

Apple Vision Selfie Detection 是一个 Flutter 插件,使 Flutter 应用能够使用 Apple Vision Selfie Segmentation。此插件并非由 Apple 赞助或维护。作者是一些希望为 macOS 开发类似 Google ML Kit 的开发者。

需求

MacOS

  • 最低 osx 部署目标:12.0
  • Xcode 13 或更新版本
  • Swift 5
  • ML Kit 只支持 64 位架构(x86_64 和 arm64)

iOS

  • 目前尚不支持开发
  • 最低 ios 部署目标:13.0
  • Xcode 13 或更新版本
  • Swift 5
  • ML Kit 只支持 64 位架构(x86_64 和 arm64)

入门指南

首先导入 'package:apple_vision_selfie/apple_vision_selfie.dart';

final GlobalKey cameraKey = GlobalKey(debugLabel: "cameraKey");
late AppleVisionSelfieController visionController = AppleVisionSelfieController();
InsertCamera camera = InsertCamera();
Size imageSize = const Size(640, 640 * 9 / 16);
String? deviceId;
bool loading = true;

List<Uint8List?>? selfieImage;
late double deviceWidth;
late double deviceHeight;

[@override](/user/override)
void initState() {
  camera.setupCameras().then((value) {
    setState(() {
      loading = false;
    });
    camera.startLiveFeed((InputImage i) {
      if (i.metadata?.size != null) {
        imageSize = i.metadata!.size;
      }
      if (mounted) {
        Uint8List? image = i.bytes;
        visionController.processImage(image!, i.metadata!.size, PictureFormat.png).then((data) {
          selfieImage = data;
          setState(() {});
        });
      }
    });
  });
  super.initState();
}

[@override](/user/override)
void dispose() {
  camera.dispose();
  super.dispose();
}

[@override](/user/override)
Widget build(BuildContext context) {
  deviceWidth = MediaQuery.of(context).size.width;
  deviceHeight = MediaQuery.of(context).size.height;
  return Stack(
    children: [
      SizedBox(
        width: imageSize.width,
        height: imageSize.height,
        child: loading ? Container() : CameraSetup(camera: camera, size: imageSize),
      ),
      if (selfieImage?[0] != null)
        SizedBox(
          width: imageSize.width,
          height: imageSize.height,
          child: Image.memory(selfieImage![0]!, fit: BoxFit.fill),
        ),
    ],
  );
}

Widget loadingWidget() {
  return Container(
    width: deviceWidth,
    height: deviceHeight,
    color: Theme.of(context).canvasColor,
    alignment: Alignment.center,
    child: const CircularProgressIndicator(color: Colors.blue),
  );
}

示例

以下是完整的示例代码,展示了如何使用 apple_vision_selfie 插件:

import 'package:apple_vision_selfie/apple_vision_selfie.dart';
import 'package:flutter/material.dart';
import '../camera/camera_insert.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'camera/input_image.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const VisionSelfie(),
    );
  }
}

class VisionSelfie extends StatefulWidget {
  const VisionSelfie({
    Key? key,
    this.onScanned,
  }) : super(key: key);

  final Function(dynamic data)? onScanned;

  [@override](/user/override)
  _VisionSelfie createState() => _VisionSelfie();
}

class _VisionSelfie extends State<VisionSelfie> {
  final GlobalKey cameraKey = GlobalKey(debugLabel: "cameraKey");
  late AppleVisionSelfieController visionController = AppleVisionSelfieController();
  InsertCamera camera = InsertCamera();
  Size imageSize = const Size(640, 640 * 9 / 16);
  String? deviceId;
  bool loading = true;

  List<Uint8List?>? selfieImage;
  late double deviceWidth;
  late double deviceHeight;
  Uint8List? bg;

  [@override](/user/override)
  void initState() {
    rootBundle.load('assets/WaterOnTheMoonFull.jpg').then((value) {
      bg = value.buffer.asUint8List();
    });
    camera.setupCameras().then((value) {
      setState(() {
        loading = false;
      });
      camera.startLiveFeed((InputImage i) {
        if (i.metadata?.size != null) {
          imageSize = i.metadata!.size;
        }
        if (mounted) {
          Uint8List? image = i.bytes;
          visionController.processImage(
            SelfieSegmentationData(
              image: image!,
              imageSize: i.metadata!.size,
              quality: SelfieQuality.fast,
              backGround: bg,
            ),
          ).then((data) {
            selfieImage = data;
            setState(() {});
          });
        }
      });
    });
    super.initState();
  }

  [@override](/user/override)
  void dispose() {
    camera.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    deviceWidth = MediaQuery.of(context).size.width;
    deviceHeight = MediaQuery.of(context).size.height;
    return ListView(
      children: [
        SizedBox(
          width: 320,
          height: 320 * 9 / 16,
          child: loading ? Container() : CameraSetup(camera: camera, size: imageSize),
        ),
        if (selfieImage?[0] != null)
          SizedBox(
            width: 320,
            height: 320 * 9 / 16,
            child: Stack(
              children: [
                Image.memory(
                  selfieImage![0]!,
                  fit: BoxFit.fitHeight,
                ),
              ],
            ),
          ),
      ],
    );
  }

  Widget loadingWidget() {
    return Container(
      width: deviceWidth,
      height: deviceHeight,
      color: Theme.of(context).canvasColor,
      alignment: Alignment.center,
      child: const CircularProgressIndicator(color: Colors.blue),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用apple_vision_selfie插件进行人脸识别的示例代码。这个插件利用Apple的Vision框架来实现人脸识别功能,但请注意,这个插件仅适用于iOS平台。

首先,确保你的Flutter项目已经设置好,并且已经添加了apple_vision_selfie依赖。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  apple_vision_selfie: ^最新版本号 # 请替换为实际最新版本号

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用apple_vision_selfie插件进行人脸识别:

  1. 导入插件

在你的Dart文件中导入apple_vision_selfie插件:

import 'package:apple_vision_selfie/apple_vision_selfie.dart';
import 'package:image_picker/image_picker.dart';

注意:由于apple_vision_selfie插件需要图片作为输入,因此这里也导入了image_picker插件来从相机或图库中获取图片。

  1. 请求相机和照片库权限

在iOS上,你需要请求访问相机和照片库的权限。这通常在应用的Info.plist文件中配置,但也可以在代码中动态请求(尽管对于apple_vision_selfie来说,主要是Info.plist配置)。

Info.plist中添加以下权限请求:

<key>NSCameraUsageDescription</key>
<string>需要访问相机以进行人脸识别</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问照片库以选择图片进行人脸识别</string>
  1. 实现人脸识别功能

下面是一个完整的示例,展示如何使用apple_vision_selfie插件进行人脸识别:

import 'package:flutter/material.dart';
import 'package:apple_vision_selfie/apple_vision_selfie.dart';
import 'package:image_picker/image_picker.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter 人脸识别示例'),
        ),
        body: FaceRecognitionScreen(),
      ),
    );
  }
}

class FaceRecognitionScreen extends StatefulWidget {
  @override
  _FaceRecognitionScreenState createState() => _FaceRecognitionScreenState();
}

class _FaceRecognitionScreenState extends State<FaceRecognitionScreen> {
  final ImagePicker _picker = ImagePicker();
  File? _imageFile;
  List<FaceRectangle>? _faceRectangles;

  Future<void> _pickImage(ImageSource source) async {
    final XFile? image = await _picker.pickImage(source: source);
    if (image != null) {
      final File imageFile = File(image.path);
      setState(() {
        _imageFile = imageFile;
      });

      // 使用apple_vision_selfie进行人脸识别
      final FaceRecognitionResult result = await AppleVisionSelfie.detectFaces(imageFile);
      setState(() {
        _faceRectangles = result.faceRectangles;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _imageFile == null
              ? Text('没有选择图片')
              : Image.file(_imageFile!),
          if (_faceRectangles != null)
            _FaceOverlay(
              image: _imageFile!,
              faceRectangles: _faceRectangles!,
            ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () => _pickImage(ImageSource.camera),
            child: Text('从相机选择'),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () => _pickImage(ImageSource.gallery),
            child: Text('从图库选择'),
          ),
        ],
      ),
    );
  }
}

class _FaceOverlay extends StatelessWidget {
  final File image;
  final List<FaceRectangle> faceRectangles;

  _FaceOverlay({required this.image, required this.faceRectangles});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Image.file(image),
        ...faceRectangles.map(
          (face) => Positioned(
            left: face.origin.x,
            top: face.origin.y,
            width: face.size.width,
            height: face.size.height,
            child: DecoratedBox(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.red, width: 2),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,用户可以从相机或图库中选择一张图片,然后使用apple_vision_selfie插件进行人脸识别。识别到的人脸会用红色的边框标记出来。

请确保在实际部署之前,仔细测试并处理可能的错误情况,比如权限被拒绝或图片处理失败等。

回到顶部