简体   繁体   English

尝试检测自定义 tflite model 上的对象时出现 PlatformException

[英]PlatformException when trying to detect objects on a custom tflite model

I used Cloud AutoML to train a custom model that suppose to detect marks on a piece of paper.我使用 Cloud AutoML 训练了一个自定义 model,它假设可以检测一张纸上的标记。 I have the dataset exported as a TFLite file, and i have it hosted on firebase.我将数据集导出为 TFLite 文件,并将其托管在 firebase 上。

I managed to download the file and initiate the objectDetector fine.我设法下载了文件并很好地启动了 objectDetector。 but are getting an error when processing an input image.但在处理输入图像时出现错误。

This is my code:这是我的代码:

Initialise the detector in the cubit初始化cubit中的检测器

  initialiseDetector({double confidenceThreshold = 0.5, int maximumLabelsPerObject = 10}) async {
    emit(ShoddyLoading(state.mainShoddyState.copyWith(message: 'Loading object detector')));
    try {
      ObjectDetector objectDetector = await ShoddyHelper.initialiseDetector(
        processingFromDownloadedFile: true,
        modelFile: state.mainShoddyState.modelFile,
        confidenceThreshold: confidenceThreshold,
        maximumLabelsPerObject: maximumLabelsPerObject,
      );
      emit(ShoddyModelLoaded(state.mainShoddyState.copyWith(objectDetector: objectDetector, message: 'Ready to start processing images')));
    } catch (error) {
      emit(ShoddyError(state.mainShoddyState.copyWith(message: error.toString())));
    }
  }

A helper / utilities file to download or use a model file用于下载或使用 model 文件的帮助程序/实用程序文件

  static Future<ObjectDetector> initialiseDetector({File? modelFile, bool processingFromDownloadedFile = true, required double confidenceThreshold, required int maximumLabelsPerObject}) async {
    if (processingFromDownloadedFile) {
      if (modelFile != null) {
        return await initializeLocalDetector(modelFile, confidenceThreshold, maximumLabelsPerObject);
      } else {
        File modelFile = await loadModelFileFromFirebase();
        return await initializeLocalDetector(modelFile, confidenceThreshold, maximumLabelsPerObject);
      }
    } else {
      return await initializeFirebaseDetector(confidenceThreshold, maximumLabelsPerObject);
    }
  }

// Download the model file from firebase first
  static Future<File> loadModelFileFromFirebase(String modelName) async {
    try {
      FirebaseModelDownloader downloader = FirebaseModelDownloader.instance;

      List<FirebaseCustomModel> models = await downloader.listDownloadedModels();
      for (FirebaseCustomModel model in models) {
        print('Name: ${model.name}');
      }

      FirebaseModelDownloadConditions conditions = FirebaseModelDownloadConditions(
        iosAllowsCellularAccess: true,
        iosAllowsBackgroundDownloading: false,
        androidChargingRequired: false,
        androidWifiRequired: false,
        androidDeviceIdleRequired: false,
      );

      FirebaseCustomModel model = await downloader.getModel(
        modelName,
        FirebaseModelDownloadType.latestModel,
        conditions,
      );

      File modelFile = model.file;

      return modelFile;
    } catch (exception) {
      print('Failed on loading your model from Firebase: $exception');
      print('The program will not be resumed');
      rethrow;
    }
  }

  // Use a file downloaded from firebase
  static Future<ObjectDetector> initializeLocalDetector(File modelFile, double confidenceThreshold, int maximumLabelsPerObject) async {
    try {
      final options = LocalObjectDetectorOptions(
        mode: DetectionMode.single,
        modelPath: modelFile.path,
        classifyObjects: true,
        multipleObjects: true,
        confidenceThreshold: confidenceThreshold,
        maximumLabelsPerObject: maximumLabelsPerObject,
      );

      return ObjectDetector(options: options);
    } catch (exception) {
      print('Failed on loading your model to the TFLite interpreter: $exception');
      print('The program will not be resumed');
      rethrow;
    }
  }

  // Use the model file directly from firebase
  static Future<ObjectDetector> initializeFirebaseDetector(String modelName, double confidenceThreshold, int maximumLabelsPerObject) async {
    try {
      final options = FirebaseObjectDetectorOptions(
        mode: DetectionMode.single,
        modelName: modelName,
        classifyObjects: true,
        multipleObjects: true,
        confidenceThreshold: confidenceThreshold,
        maximumLabelsPerObject: maximumLabelsPerObject,
      );

      return ObjectDetector(options: options);
    } catch (exception) {
      print('Failed on loading your model to the TFLite interpreter: $exception');
      print('The program will not be resumed');
      rethrow;
    }
  }

The function to process an image function 处理图像

  processImage(File file) async {
    emit(ShoddyModelProcessing(state.mainShoddyState.copyWith(message: 'Looking for objects on the selected image')));
    try {
      List<dynamic>? results = [];
      if (state.mainShoddyState.objectDetector != null) {
        InputImage inputImage = InputImage.fromFilePath(file.path);
        List<DetectedObject> objects = await state.mainShoddyState.objectDetector!.processImage(inputImage);
        if (objects.isNotEmpty) {
          List<ObjectModel> objects = results.map((result) => ObjectModel(result)).toList();
          emit(ShoddyModelProcessed(state.mainShoddyState.copyWith(objects: objects, filteredObjects: objects, message: 'Image processed with results')));
          changeMatchPercentage(0.35);
        } else {
          emit(ShoddyModelProcessed(state.mainShoddyState.copyWith(objects: [], filteredObjects: [], message: 'Image processed with no results')));
        }
      }
    } catch (error) {
      emit(ShoddyError(state.mainShoddyState.copyWith(message: error.toString())));
    }
  }

When i call:当我打电话时:

        List<DetectedObject> objects = await state.mainShoddyState.objectDetector!.processImage(inputImage);

I get the following error:我收到以下错误:

PlatformException(Error 3, com.google.visionkit.pipeline.error, Pipeline failed to fully start:
CalculatorGraph::Run() failed in Run: 
Calculator::Open() for node "BoxClassifierCalculator" failed: #vk Unexpected number of dimensions for output index 0: got 3D, expected either 2D (BxN with B=1) or 4D (BxHxWxN with B=1, W=1, H=1)., null)

Is there something i'm missing?有什么我想念的吗?

You have exported the model (not the database) as a TFLite model.您已将 model(不是数据库)导出为 TFLite model。 And you are using MLKit's detection API.而你正在使用 MLKit 的检测 API。

In order for a TFLite model to be compatible with MLKit, it needs to accept 2-dimensional or 4-dimensional tensors, as documented here .为了使 TFLite model 与 MLKit 兼容,它需要接受 2 维或 4 维张量,如此所述。

The exported model seems to accept a 3d tensor.导出的 model 似乎接受 3d 张量。 The solution is to go back to the tool you used to develop the model and ensure the model interface is 4-d, with the specs according to this document .解决方法是将 go 恢复到您用于开发 model 的工具,并确保 model 接口为 4-d,规格根据本文档

According to the ML kit documents its not possible to do object detection with AutoML Vision custom trained object detection models根据机器学习套件文件,不可能使用 AutoML Vision 定制训练的 object 检测模型进行 object 检测

https://developers.google.com/ml-kit/custom-models#automl_vision_edge https://developers.google.com/ml-kit/custom-models#automl_vision_edge

Note: ML Kit only supports custom image classification models. Although AutoML Vision allows training of object detection models, these cannot be used with ML Kit.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10:, null, null) 尝试在 flutter 中使用 googleSignIn 时 - PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null) When trying to use googleSignIn in flutter PlatformException (PlatformException(channel-error, Unable to establish connection on channel., null, null)) WHEN 在 Flutter 上设置登录 - PlatformException (PlatformException(channel-error, Unable to establish connection on channel., null, null)) WHEN setting up login on Flutter 如何在树莓派上运行使用 GCP 训练的 TFLITE model - How to run a TFLITE model trained using GCP on raspberry Pi Firebase PlatformException 错误不工作 - Firebase on PlatformException Error Not working ValueError:未找到 SavedModel 包。 尝试将 TF2.0 模型部署到 SageMaker 时 - ValueError: no SavedModel bundles found! when trying to deploy a TF2.0 model to SageMaker Flutter:使用自定义模型进行测试 - Flutter: testing with custom model Flutter Google 登录不工作平台异常 - Flutter Google Sign-In not working platformexception Flutter model for FireBase - 添加对象列表 - Flutter model for FireBase - add a List of objects 如何使用 FirebaseFirestoreSwift 读取自定义对象 - How to use FirebaseFirestoreSwift for read Custom objects FirebaseCloudMessaging: PlatformException (PlatformException(null-error, Host platform returned null value for non-null return value., null, null)) - FirebaseCloudMessaging : PlatformException (PlatformException(null-error, Host platform returned null value for non-null return value., null, null))
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM