Flutter图像分类插件apple_vision_image_classification的使用

Flutter图像分类插件apple_vision_image_classification的使用

apple_vision_image_classification

Pub Version analysis Star on Github License: MIT

Apple Vision 自拍照检测是一个使 Flutter 应用能够使用 Apple Vision 图像分类 的插件。

  • 该插件不是由 Apple 赞助或维护。作者是希望为 macOS 创建类似 Google ML Kit 插件的开发者。

需求

MacOS

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

iOS

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

开始使用

首先导入 'package:apple_vision/apple_vision.dart'

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

List<Label>? labels;
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!, imageSize).then((data) {
          labels = 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: <Widget>[
      SizedBox(
        width: imageSize.width,
        height: imageSize.height,
        child: loading ? Container() : CameraSetup(camera: camera, size: imageSize)
      ),
      Column(children: showLabel(),)
    ]
  );
}

List<Widget> showLabel() {
  if (labels == null || labels!.isEmpty) return [];
  List<Widget> widgets = [];

  for (int i = 0; i < labels!.length; i++) {
    widgets.add(
      Container(
        width: 320,
        height: 20,
        decoration: BoxDecoration(
          color: Colors.green,
          borderRadius: BorderRadius.circular(5)
        ),
        child: Text(
          '${labels![i].label}: ${labels![i].confidence}',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 12
          ),
        ),
      )
    );
  }
  return widgets;
}

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

示例

以下是该插件的一个完整示例:

import 'package:apple_vision_image_classification/apple_vision_image_classification.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 VisionIC(),
    );
  }
}

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

  final Function(dynamic data)? onScanned;

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

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

  List<Label>? labels;
  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!, imageSize).then((data) {
            labels = 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: <Widget>[
        SizedBox(
          width: imageSize.width,
          height: imageSize.height,
          child: loading ? Container() : CameraSetup(camera: camera, size: imageSize)
        ),
        Column(children: showLabel(),)
      ]
    );
  }

  List<Widget> showLabel() {
    if (labels == null || labels!.isEmpty) return [];
    List<Widget> widgets = [];

    for (int i = 0; i < labels!.length; i++) {
      widgets.add(
        Container(
          width: 320,
          height: 20,
          decoration: BoxDecoration(
            color: Colors.green,
            borderRadius: BorderRadius.circular(5)
          ),
          child: Text(
            '${labels![i].label}: ${labels![i].confidence}',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12
            ),
          ),
        )
      );
    }
    return widgets;
  }

  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_image_classification的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter图像分类插件apple_vision_image_classification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


apple_vision_image_classification 是一个 Flutter 插件,用于在 iOS 设备上使用 Apple 的 Vision 框架进行图像分类。这个插件允许你在 Flutter 应用中轻松地集成图像分类功能。以下是如何使用这个插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  apple_vision_image_classification: ^1.0.0  # 请检查最新版本

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

2. 导入插件

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

import 'package:apple_vision_image_classification/apple_vision_image_classification.dart';

3. 初始化插件

在使用插件之前,你需要初始化它。通常你可以在 initState 方法中进行初始化:

class _MyHomePageState extends State<MyHomePage> {
  AppleVisionImageClassification? _imageClassification;

  [@override](/user/override)
  void initState() {
    super.initState();
    _imageClassification = AppleVisionImageClassification();
  }

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

4. 加载图像并进行分类

你可以使用 classifyImage 方法来对图像进行分类。以下是一个简单的示例:

Future<void> classifyImage(String imagePath) async {
  try {
    final classificationResult = await _imageClassification!.classifyImage(imagePath);
    print('Classification Result: $classificationResult');
  } catch (e) {
    print('Error: $e');
  }
}

5. 处理分类结果

classifyImage 方法返回一个包含分类结果的列表。每个结果通常包含一个标签和置信度分数。你可以根据需要处理这些结果:

classificationResult.forEach((result) {
  print('Label: ${result.label}, Confidence: ${result.confidence}');
});

6. 完整示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 apple_vision_image_classification 插件:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Classification',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  AppleVisionImageClassification? _imageClassification;

  [@override](/user/override)
  void initState() {
    super.initState();
    _imageClassification = AppleVisionImageClassification();
  }

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

  Future<void> classifyImage(String imagePath) async {
    try {
      final classificationResult = await _imageClassification!.classifyImage(imagePath);
      print('Classification Result: $classificationResult');
      classificationResult.forEach((result) {
        print('Label: ${result.label}, Confidence: ${result.confidence}');
      });
    } catch (e) {
      print('Error: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Classification'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                // 替换为你的图像路径
                await classifyImage('assets/sample_image.jpg');
              },
              child: Text('Classify Image'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部