Flutter华为机器学习图像识别插件huawei_ml_image的使用

华为ML图像Flutter插件

pub.dev版本


华为ML Kit图像Flutter插件提供了来自华为ML Kit SDK的API。该插件包含以下API:

  • 图像分类
  • 图像分割
  • 地标识别
  • 物体检测
  • 场景检测
  • 文档倾斜校正
  • 图像超分辨率
  • 文本图像超分辨率

了解更多:快速入门

安装 #

请参阅pub.devAppGallery Connect配置

文档 #

问题或问题反馈 #

如果您在如何使用HMS样本时遇到问题,请尝试以下选项:

  • Stack Overflow 是任何编程问题的最佳场所。请确保将您的问题标记为 huawei-mobile-services
  • GitHub 是这些插件的官方仓库,您可以在此处提交问题或提出建议。
  • 华为开发者论坛 HMS核心模块非常适合一般问题,或者寻求推荐和意见。
  • 华为开发者文档 是所有HMS核心工具包的官方文档所在位置,您可以在那里找到详细文档。

如果您在我们的样本中遇到错误,请向 GitHub仓库 提交问题。

许可证 #

华为ML图像Flutter插件是在 Apache 2.0许可证 下授权的。

example/lib/main.dart

/*
    Copyright 2021-2024. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

import ‘package:flutter/material.dart’; import ‘package:flutter/services.dart’; import ‘package:huawei_ml_image/huawei_ml_image.dart’; import ‘package:huawei_ml_image_example/screens/home.dart’;

void main() async { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations( <DeviceOrientation>[ DeviceOrientation.portraitUp, ], ); // TODO: 在您的agconnect-services.json文件中复制并粘贴api_key值。 await MLImageApplication().setApiKey(’<api_key>’); await requestPermissions(); runApp(const MyApp()); }

// TODO: 请实现您自己的’权限处理程序’。 Future<void> requestPermissions() async { // 此插件需要一些权限才能正常工作。 // 您需要处理这些权限以使用此Demo。

// 您可以从我们的官方文档中了解所需权限的更多信息。 // https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/assigning-permissions-0000001052789343?ha_source=hms1 }

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

@override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: Home(), ); } }


更多关于Flutter华为机器学习图像识别插件huawei_ml_image的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter华为机器学习图像识别插件huawei_ml_image的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用huawei_ml_image插件进行图像识别的示例代码。这个插件允许你利用华为机器学习服务进行图像识别。

首先,你需要在你的Flutter项目中添加huawei_ml_image依赖。打开你的pubspec.yaml文件,并添加以下依赖:

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

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

接下来,你需要在android/app/build.gradle文件中添加华为机器学习服务的配置:

android {
    ...
    defaultConfig {
        ...
        applicationId "your.package.name"  // 替换为你的应用ID
        ...
        // 添加以下配置
        manifestPlaceholders = [
                'app_id' : 'your_huawei_app_id',  // 替换为你的华为应用ID
                'channel' : 'huawei'
        ]
    }
    ...
}

dependencies {
    ...
    implementation 'com.huawei.hms:ml-computer-vision-image-classification:2.0.3.300'  // 请根据需要选择版本
}

android/app/src/main/AndroidManifest.xml中,确保你有必要的权限和服务连接:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        ...
        >
        ...
        <meta-data
            android:name="com.huawei.hms.client.appid"
            android:value="${app_id}" />
    </application>
</manifest>

然后,你可以在你的Flutter代码中使用huawei_ml_image插件进行图像识别。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:huawei_ml_image/huawei_ml_image.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('Huawei ML Image Recognition'),
        ),
        body: ImageRecognitionPage(),
      ),
    );
  }
}

class ImageRecognitionPage extends StatefulWidget {
  @override
  _ImageRecognitionPageState createState() => _ImageRecognitionPageState();
}

class _ImageRecognitionPageState extends State<ImageRecognitionPage> {
  File? _imageFile;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _imageFile == null
              ? Text('No image selected.')
              : Image.file(_imageFile!),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _pickImage,
            child: Text('Pick Image'),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _recognizeImage,
            child: Text('Recognize Image'),
            enabled: _imageFile != null,
          ),
          SizedBox(height: 16),
          Text('Recognition Result: $_recognitionResult', style: TextStyle(fontSize: 16)),
        ],
      ),
    );
  }

  String _recognitionResult = '';

  Future<void> _pickImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.camera);

    setState(() {
      _imageFile = File(pickedFile!.path);
    });
  }

  Future<void> _recognizeImage() async {
    if (_imageFile == null) return;

    try {
      final result = await MLImageRecognition.analyzeImage(_imageFile!.path);
      setState(() {
        _recognitionResult = result.toString();  // 根据需要处理结果
      });
    } catch (e) {
      setState(() {
        _recognitionResult = 'Error: ${e.message}';
      });
    }
  }
}

在这个示例中,我们使用了image_picker插件来选择图像。huawei_ml_image插件用于分析图像并返回识别结果。

请注意,MLImageRecognition.analyzeImage方法的具体返回类型和结构可能会根据插件的版本和华为机器学习服务的更新而变化。因此,你可能需要查阅最新的文档或插件的源代码来了解如何处理返回的结果。

另外,由于华为服务可能需要特定的API密钥和配置,请确保你已经按照华为开发者文档完成了所有必要的设置。

回到顶部