当前位置: 首页 > 知识库问答 >
问题:

向颤振项目发布装载资产

楚德辉
2023-03-14

我试图将TFLite模型加载到颤振中,但出现异常“加载模型失败”。我已经通过yaml加载了资产,导入了TFLite插件,并确保文件路径正确,但我一直打印相同的异常。我已经用python测试了这个模型,它可以工作了,所以我现在只是想让它与颤振一起工作。

代码:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tflite/tflite.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as img;

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

const String TF = "image_classifier";
//const String yolo = "Tiny YOLOv2";

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: TfliteHome(),
    );
  }
}

class TfliteHome extends StatefulWidget {
  @override
  _TfliteHomeState createState() => _TfliteHomeState();
}

class _TfliteHomeState extends State<TfliteHome> {
  String _model = TF;
  File _image;

  double _imageWidth;
  double _imageHeight;
  bool _busy = false;

  List _recognitions;

  @override
  void initState() {
    super.initState();
    _busy = true;

    loadModel().then((val) {
      setState(() {
        _busy = false;
      });
    });
  }

  loadModel() async {
    Tflite.close();
    try {
      String res;
        res = await Tflite.loadModel(
          model: "assets/image_classifier.tflite",
          labels: "assets/image_labels.txt",
        );
      print(res);
    } on PlatformException {
      print("Failed to load the model");
    }
  }

  selectFromImagePicker() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (image == null) return;
    setState(() {
      _busy = true;
    });
    predictImage(image);
  }

  predictImage(File image) async {
    if (image == null) return;

    if (_model == TF) {
      await TFModel(image);
    }

    FileImage(image)
        .resolve(ImageConfiguration())
        .addListener((ImageStreamListener((ImageInfo info, bool _) {
          setState(() {
            _imageWidth = info.image.width.toDouble();
            _imageHeight = info.image.height.toDouble();
          });
        })));

    setState(() {
      _image = image;
      _busy = false;
    });
  }

  TFModel(File image) async {
    var recognitions = await Tflite.detectObjectOnImage(
        path: image.path,
        model: "image_classifier",
        threshold: 0.3,
        imageMean: 0.0,
        imageStd: 255.0,
        numResultsPerClass: 3);

    setState(() {
      _recognitions = recognitions;
    });
  }

  List<Widget> renderBoxes(Size screen) {
    if (_recognitions == null) return [];
    if (_imageWidth == null || _imageHeight == null) return [];

    double factorX = screen.width;
    double factorY = _imageHeight / _imageHeight * screen.width;

    Color blue = Colors.red;

    return _recognitions.map((re) {
      return Positioned(
        left: re["rect"]["x"] * factorX,
        top: re["rect"]["y"] * factorY,
        width: re["rect"]["w"] * factorX,
        height: re["rect"]["h"] * factorY,
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(
            color: blue,
            width: 3,
          )),
          child: Text(
            "${re["detectedClass"]} ${(re["confidenceInClass"] * 100).toStringAsFixed(0)}%",
            style: TextStyle(
              background: Paint()..color = blue,
              color: Colors.white,
              fontSize: 15,
            ),
          ),
        ),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    List<Widget> stackChildren = [];

    stackChildren.add(Positioned(
      top: 0.0,
      left: 0.0,
      width: size.width,
      child: _image == null ? Text("No Image Selected") : Image.file(_image),
    ));

    stackChildren.addAll(renderBoxes(size));

    if (_busy) {
      stackChildren.add(Center(
        child: CircularProgressIndicator(),
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text("TFLite Demo"),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.image),
        tooltip: "Pick Image from gallery",
        onPressed: selectFromImagePicker,
      ),
      body: Stack(
        children: stackChildren,
      ),
    );
  }
}

公共规范。亚马尔:

flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
  - assets/image_classifier.tflite
  - assets/image_labels.txt

共有2个答案

杨凌
2023-03-14

我想:

assets:
  - assets/image_classifier.tflite // also not the two-space indentation
  - assets/image_labels.txt

路径中应该没有“资产”。

assets:
  - image_classifier.tflite
  - image_labels.txt
潘安平
2023-03-14

Android在android/app/build.gradle中,在android块中添加以下设置。

  aaptOptions {
    noCompress 'tflite'
    noCompress 'lite'
}

为我工作!!

 类似资料:
  • 我可以从flutter应用程序的assets/Images目录加载图像,但当从flutter包的assets/Images目录加载相同的图像时,我会得到以下错误:

  • 我用grpc创建了颤振项目,但在尝试从proto生成文件dart时出错。我将proto文件放在lib/protos(rewards.proto)中,然后放在终端put命令“protoc--dart\u out=grpc:lib/src-Iprotos protos/rewards”中。proto' 我的接收器错误是这样的——dart_out:proc-gen-dart: ═х єфрхЄё 我做错

  • 我试图创建一个ListView,但当我导入list_form.dart类时,我得到了这个错误。也许我在布局上犯了一些错误,因为如果我尝试在主文件中运行它,我不会得到这个错误。 这是错误: 这是list\u表单。dart等级: 这是app_base.dart类: 不要担心是否有一些未使用的代码,它是半成品,这个错误只是阻止了我继续我正在做的事情。

  • 我读过https://flutter.dev/docs/development/ui/assets-and-images#asset-包依赖项中的图像和从资产中读取的文本文件,并应用了所有这些,但我的代码仍然无法工作。。。。 我为此打开了一个新项目,在主文件夹中创建了资产和文件: 然后,不信任Android Studio,我检查了vi,在pubspec.yaml一切都好: 该文件以以下内容结尾:

  • 我创建了一个新的应用程序。 从https://pub.dev/packages/audioplayers添加了audioplayers flutter包。 显示Android嵌入的错误。我按照说明https://flutter.dev/go/android-project-migration进行操作。 现在我得到这个错误:

  • 目前我正在尝试颤振网页,我需要在颤振主频道工作。但是,后来我需要继续我的其他项目。在他们身上,我正在研究颤振稳定通道。 但是,每当我使用命令“flutter channel stable”或“fluter channel master”切换我的flutter通道时,它每次都会重新下载sdk和其他工具。 目前,我已经下载了稳定的颤振sdk和稳定的dart sdk。 我已将它们移动到“FlutterS