Code Monkey home page Code Monkey logo

tflite_flutter_helper's Introduction

TensorFlow Lite Flutter Helper Library

TFLite Flutter Helper Library brings TFLite Support Library and TFLite Support Task Library to Flutter and helps users to develop ML and deploy TFLite models onto mobile devices quickly without compromising on performance.

Getting Started

Setup TFLite Flutter Plugin

Follow the initial setup instructions given here

Basic image manipulation and conversion

TFLite Helper depends on flutter image package internally for Image Processing.

The TensorFlow Lite Support Library has a suite of basic image manipulation methods such as crop and resize. To use it, create an ImageProcessor and add the required operations. To convert the image into the tensor format required by the TensorFlow Lite interpreter, create a TensorImage to be used as input:

// Initialization code
// Create an ImageProcessor with all ops required. For more ops, please
// refer to the ImageProcessor Ops section in this README.
ImageProcessor imageProcessor = ImageProcessorBuilder()
  .add(ResizeOp(224, 224, ResizeMethod.NEAREST_NEIGHBOUR))
  .build();

// Create a TensorImage object from a File
TensorImage tensorImage = TensorImage.fromFile(imageFile);

// Preprocess the image.
// The image for imageFile will be resized to (224, 224)
tensorImage = imageProcessor.process(tensorImage);

Sample app: Image Classification

Basic audio data processing

The TensorFlow Lite Support Library also defines a TensorAudio class wrapping some basic audio data processing methods.

TensorAudio tensorAudio = TensorAudio.create(
    TensorAudioFormat.create(1, sampleRate), size);
tensorAudio.loadShortBytes(audioBytes);

TensorBuffer inputBuffer = tensorAudio.tensorBuffer;

Sample app: Audio Classification

Create output objects and run the model

// Create a container for the result and specify that this is a quantized model.
// Hence, the 'DataType' is defined as UINT8 (8-bit unsigned integer)
TensorBuffer probabilityBuffer =
    TensorBuffer.createFixedSize(<int>[1, 1001], TfLiteType.uint8);

Loading the model and running inference:

import 'package:tflite_flutter/tflite_flutter.dart';

try {
    // Create interpreter from asset.
    Interpreter interpreter =
        await Interpreter.fromAsset("mobilenet_v1_1.0_224_quant.tflite");
    interpreter.run(tensorImage.buffer, probabilityBuffer.buffer);
} catch (e) {
    print('Error loading model: ' + e.toString());
}

Accessing the result

Developers can access the output directly through probabilityBuffer.getDoubleList(). If the model produces a quantized output, remember to convert the result. For the MobileNet quantized model, the developer needs to divide each output value by 255 to obtain the probability ranging from 0 (least likely) to 1 (most likely) for each category.

Optional: Mapping results to labels

Developers can also optionally map the results to labels. First, copy the text file containing labels into the module’s assets directory. Next, load the label file using the following code:

List<String> labels = await FileUtil.loadLabels("assets/labels.txt");

The following snippet demonstrates how to associate the probabilities with category labels:

TensorLabel tensorLabel = TensorLabel.fromList(
      labels, probabilityProcessor.process(probabilityBuffer));

Map<String, double> doubleMap = tensorLabel.getMapWithFloatValue();

ImageProcessor Architecture

The design of the ImageProcessor allowed the image manipulation operations to be defined up front and optimised during the build process. The ImageProcessor currently supports three basic preprocessing operations:

int cropSize = min(_inputImage.height, _inputImage.width);

ImageProcessor imageProcessor = ImageProcessorBuilder()
    // Center crop the image to the largest square possible
    .add(ResizeWithCropOrPadOp(cropSize, cropSize))
    // Resize using Bilinear or Nearest neighbour
    .add(ResizeOp(224, 224, ResizeMethod.NEAREST_NEIGHBOUR))
    // Rotation clockwise in 90 degree increments
    .add(Rot90Op(rotationDegrees ~/ 90))
    .add(NormalizeOp(127.5, 127.5))
    .add(QuantizeOp(128.0, 1 / 128.0))
    .build();

See more details here about normalization and quantization.

Quantization

The TensorProcessor can be used to quantize input tensors or dequantize output tensors. For example, when processing a quantized output TensorBuffer, the developer can use DequantizeOp to dequantize the result to a floating point probability between 0 and 1:

// Post-processor which dequantize the result
TensorProcessor probabilityProcessor =
    TensorProcessorBuilder().add(DequantizeOp(0, 1 / 255.0)).build();
TensorBuffer dequantizedBuffer =
    probabilityProcessor.process(probabilityBuffer);

Reading Qunatization Params

// Quantization Params of input tensor at index 0
QuantizationParams inputParams = interpreter.getInputTensor(0).params;

// Quantization Params of output tensor at index 0
QuantizationParams outputParams = interpreter.getOutputTensor(0).params;

Task Library

Currently, Text based models like NLClassifier, BertNLClassifier and BertQuestionAnswerer are available to use with the Flutter Task Library.

Integrate Natural Langugae Classifier

The Task Library's NLClassifier API classifies input text into different categories, and is a versatile and configurable API that can handle most text classification models. Detailed guide is available here.

final classifier = await NLClassifier.createFromAsset('assets/$_modelFileName',
        options: NLClassifierOptions());
List<Category> predictions = classifier.classify(rawText);

Sample app: Text Classification.

Integrate BERT natural language classifier

The Task Library BertNLClassifier API is very similar to the NLClassifier that classifies input text into different categories, except that this API is specially tailored for Bert related models that require Wordpiece and Sentencepiece tokenizations outside the TFLite model. Detailed guide is available here.

final classifier = await BertNLClassifier.createFromAsset('assets/$_modelFileName',
        options: BertNLClassifierOptions());
List<Category> predictions = classifier.classify(rawText);

Integrate BERT question answerer

The Task Library BertQuestionAnswerer API loads a Bert model and answers questions based on the content of a given passage. For more information, see the documentation for the Question-Answer model here. Detailed guide is available here.

final bertQuestionAnswerer = await BertQuestionAnswerer.createFromAsset('assets/$_modelFileName');
List<QaAnswer> answeres = bertQuestionAnswerer.answer(context, question);

Sample app: Bert Question Answerer Sample

tflite_flutter_helper's People

Contributors

am15h avatar mdejeans avatar t-nakaichi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tflite_flutter_helper's Issues

Size of bounding box dimBouBoxension 0 is not 4. Got 1 in shape [1, 10]

I'm using custom SSD Mobilenet V2 model and got an error on this part of the code:

image

The error goes like this:

Invalid argument(s): Axis 3 is not in range (-(D+1), D), where D is the number of dimensions of input tensor (shape=[1, 10]) E/flutter (16839): #0 SupportPreconditions.checkArgument (package:tflite_flutter_helper/src/common/support_preconditions.dart:16:7) E/flutter (16839): #1 BoundingBoxUtils.convert (package:tflite_flutter_helper/src/image/bounding_box_utils.dart:64:26) E/flutter (16839): #2 Classifier.predict (package:object_detection/tflite/classifier.dart:152:45) E/flutter (16839): #3 IsolateUtils.entryPoint (package:object_detection/utils/isolate_utils.dart:45:51) E/flutter (16839): <asynchronous suspension>

So i changed the value from 2 to 0 but got this error instead

[ERROR:flutter/runtime/dart_isolate.cc(1138)] Unhandled exception: E/flutter (19024): Invalid argument(s): Size of bounding box dimBouBoxension 0 is not 4. Got 1 in shape [1, 10] E/flutter (19024): #0 SupportPreconditions.checkArgument (package:tflite_flutter_helper/src/common/support_preconditions.dart:16:7) E/flutter (19024): #1 BoundingBoxUtils.convert (package:tflite_flutter_helper/src/image/bounding_box_utils.dart:74:26) E/flutter (19024): #2 Classifier.predict (package:object_detection/tflite/classifier.dart:152:45) E/flutter (19024): #3 IsolateUtils.entryPoint (package:object_detection/utils/isolate_utils.dart:45:51) E/flutter (19024): <asynchronous suspension>

Is there anything wrong with my model?

neural style transfer

HI,
I am trying to modify your example to run my neural transfer model, I am new to flutter/mobile app development. My model takes input a bgr image and returns a bgr image as output. How do I update the image selected by user with the output image. Also can you guide me about rgb to bgr conversion. I get how to resize and apply normalization. Thanks

Error when trying to use the tflite_flutter_helper package

e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\tflite_flutter_helper-0.3.1\android\src\main\kotlin\com\tfliteflutter\tflite_flutter_helper\TfliteFlutterHelperPlugin.kt: (43, 1): Class 'TfliteFlutterHelperPlugin' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult(p0: Int, p1: Array<(out) String!>, p2: IntArray): Boolean defined in io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\tflite_flutter_helper-0.3.1\android\src\main\kotlin\com\tfliteflutter\tflite_flutter_helper\TfliteFlutterHelperPlugin.kt: (143, 2): 'onRequestPermissionsResult' overrides nothing

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':tflite_flutter_helper:compileDebugKotlin'.

Compilation error. See log for more details

  • Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Upgrade Image Dependency

This package is preventing me from upgrading other packages due to version dependency conflicts! Please resolve and re-release.

Audio Classification for iOS can not work.

I tried to run Audio Classification sample on an iPhone device, but the following error was reported.

2021-12-07 21:30:21.345386+0800 Runner[6489:1451148] Metal API Validation Enabled
2021-12-07 21:30:21.620632+0800 Runner[6489:1451148] Writing analzed variants.
2021-12-07 21:30:23.421563+0800 Runner[6489:1451433] flutter: Observatory listening on http://127.0.0.1:65483/ofEKVF1edXI=/
2021-12-07 21:30:24.374794+0800 Runner[6489:1451408] [VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method initializeRecorder on channel com.tfliteflutter.tflite_flutter_helper:methods)
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
<asynchronous suspension>
#1      Future.wait.<anonymous closure> (dart:async/future.dart)
<asynchronous suspension>
#2      _MyAppState.initPlugin (package:audio_classification/main.dart:80:5)
<asynchronous suspension>
2021-12-07 21:30:24.397613+0800 Runner[6489:1451408] Op builtin_code out of range: 135. **Are you using old TFLite binary with newer model?**
2021-12-07 21:30:24.397672+0800 Runner[6489:1451408] Registration failed.
2021-12-07 21:30:24.398182+0800 Runner[6489:1451408] flutter: Unable to create interpreter, Caught Exception: Invalid argument(s): Unable to create interpreter.
2021-12-07 21:30:25.095256+0800 Runner[6489:1451408] [VERBOSE-2:ui_dart_state.cc(209)] Unhandled

High latency of Image Processor due to NormalizeOp

Any ideas why the latency of applying an image processor to a tensor image varies so drastically?

runs: 100
avg: 532ms
min: 24ms
max: 7566ms

plt

Code to reproduce:

import 'dart:typed_data';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' hide Image;
import 'package:image/image.dart';
import 'package:tflite_flutter_helper/tflite_flutter_helper.dart';

main() async {
  WidgetsFlutterBinding.ensureInitialized();

  Image image = decodeImage(
    (await rootBundle.load("assets/images/test.JPG")).buffer.asUint8List(),
  );

  ImageProcessor imageProcessor = ImageProcessorBuilder()
      .add(ResizeOp(300, 300, ResizeMethod.BILINEAR))
      .add(NormalizeOp(127.5, 127.5))
      .build();

  int min;
  int max;
  int total = 0;
  int runs = 100;

  for (int i = 0; i < runs; i++) {
    TensorImage tensorImage = TensorImage.fromImage(image);
    int t1 = DateTime.now().millisecondsSinceEpoch;
    ByteBuffer input = imageProcessor.process(tensorImage).buffer;
    int t2 = DateTime.now().millisecondsSinceEpoch;
    int dt = t2 - t1;
    total += dt;
    if (min == null || dt < min) min = dt;
    if (max == null || dt > max) max = dt;
  }

  print("runs: $runs");
  print("avg: ${total ~/ runs}ms");
  print("min: ${min}ms");
  print("max: ${max}ms");
}

install.bat didn't wok

Hello, I started a new flutter project and put the install.bat in the root, but nothing happens. Can someone help me? please.

I tried from the cmd and got the message 'GETOPT' is not a recognized command. Tried to look in google, but found no answer.

is there a tutorial for noobs?

ImageProcessor doesn't run through tasks during process since 0.3.1

I'm running a custom Yolov4 model (also a Yolo3 for what it's worth) through here. Everything was lovely while I ran tflite_flutter 0.8.0 with 0.2.0 the helper. Since upgrading to 0.9.0 and 0.3.1, I don't get a suitable image input to run through the predictor, and it winds up breaking.

More specifically, I pre-process the camera frame after it's been wrapped in a TensorImage, and send it through the ImageProcessor--

and afterwards, in runForMultipleInputs, I getInputTensors and then try to run inputTensors.elementAt(i).setTo()inputs[i]). But there's an error from within setTo()-- one of the checks fails and throws a Bad state: failed precondition.

Back during image prep, I run the ImageProcessor from this helper lib like this:

imageProcessor ??= ImageProcessorBuilder()
.add(ResizeWithCropOrPadOp(padSize!, padSize!))
.add(ResizeOp(INPUT_SIZE.toInt(), INPUT_SIZE.toInt(), ResizeMethod.NEAREST_NEIGHBOUR))
.add(NormalizeOp(1, 255))
.build();

inputImage = imageProcessor!.process(inputImage);

I think I've isolated the problem.

  • In the functional app running the old libraries, I can print out what's happening as it runs through these operations in image_processor.dart. I see the rects and the points forming as it goes.

  • When I run the updated libs, it does make an instance of the ImageProcessor, and that instance does have an operator list and an operator index that look like you'd expect. But I don't get any output when I try to print the actually running operations in image_processor.dart . No rects or points. Nothing there. i can wrap things in try / catches and it doesn't hit them. It doesn't seem to run through them at all when i run imageProcesor!.process(inputImage) (with a TensorImage wrapping an im.Image that converted correctly from a camera frame image as inputImage).

  • NOTE though: if I print out what's happening in the actual process() function in sequential_processor.dart it is iteratring through the list there and returning an instance of TensorImage at the bottom.If I wrap the little loop inside process() in a try catch, it doesn't throw anything and proceeds on to the bottom. But again, nothing in image_processor.dart, no points or rects.

After running the TensorImage wrapped im.Image through the processor in the functional app using the older libs, I can no longer see the image as an im.image-- it's a float-value image instead and throws an error if I try to access image properties. However, in the non-functionla app with the newer libs, I can still see the image afterward, thogh it's byte length is slightly more than half of what it had been.

Any insight would be appreciated... Is the idea just to run those ops manually, do you think? Or has anyone run into anything like this?

Is it possible to get values from TensorBuffer in a way other than .getDoubleList()?

Hi,

I have a NLP network that returns output in the shape [1][64][5027]. I preallocate a list for this before giving to interpreter.run() but that is very slow, so I hope that using TensorBuffer can help speed this up a bit.

Currently, I access the output logits using output[0][63] to get the last list of size 5027. But I cannot seem to do this when using TensorBuffer as the function outputBuffer.getDoubleList() returns a flat list of all the elements. This is not what I want..

So, using TensorBuffer is there a way to access the output as outputBuffer[0][63]?

Thank you

Unhandled Exception: Bad state: failed precondition

[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: failed precondition
E/flutter ( 776): #0 checkState (package:quiver/check.dart:73:5)
E/flutter ( 776): #1 Tensor.setTo (package:tflite_flutter/src/tensor.dart:150:5)
E/flutter ( 776): #2 Interpreter.runForMultipleInputs (package:tflite_flutter/src/interpreter.dart:194:33)
E/flutter ( 776): #3 Interpreter.run (package:tflite_flutter/src/interpreter.dart:165:5)
E/flutter ( 776): #4 Classifier.predict (package:fluttertfliteapp/Classifier.dart:137:17)
E/flutter ( 776): #5 _MyHomePageState._predict (package:fluttertfliteapp/main.dart:86:28)
E/flutter ( 776): #6 _MyHomePageState.getImage. (package:fluttertfliteapp/main.dart:79:7)
E/flutter ( 776): #7 State.setState (package:flutter/src/widgets/framework.dart:1267:30)
E/flutter ( 776): #8 _MyHomePageState.getImage (package:fluttertfliteapp/main.dart:73:5)
E/flutter ( 776):
E/flutter ( 776):
D/EGL_emulation( 776): eglMakeCurrent: 0xec5697e0: ver 2 0 (tinfo 0xd3994710)
D/EGL_emulation( 776): eglMakeCurrent: 0xec569060: ver 2 0 (tinfo 0xec474b90)

Precondition failed when attempting to use with a custom model

Hi, I am trying to use the library with a custom model that takes an image at the input and produces a mask at the output; it was originally converted from PyTorch. The model in question is u2net which removes backgrounds from images.

I get the following error when invoking interpreter.run:

E/flutter ( 3988): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: failed precondition
E/flutter ( 3988): #0      checkState (package:quiver/check.dart:74:5)
E/flutter ( 3988): #1      Tensor.setTo (package:tflite_flutter/src/tensor.dart:146:5)
E/flutter ( 3988): #2      Interpreter.runForMultipleInputs (package:tflite_flutter/src/interpreter.dart:186:33)
E/flutter ( 3988): #3      Interpreter.run (package:tflite_flutter/src/interpreter.dart:157:5)
E/flutter ( 3988): #4      removeBackground (bgremover_local_ex.dart:58:17)
E/flutter ( 3988): <asynchronous suspension>

I assume the problem is in incorrectly formatted input data, but through experimentation I've ruled out the obvious issues, so I've reached the stage where I'd like to get some troubleshooting tips from others.

Here are some relevant context details:

  • the input is of the form TfLiteType.float32, shape: [1, 320, 320, 3], data: 1228800] (a 320x320 image in RGB)
  • the output is TfLiteType.float32, shape: [1, 320, 320, 1], data: 409600 (a grayscale 320x320 image)

Here's an outline of what I do

    final interpreter = await tfl.Interpreter.fromAsset(
        'magic_float32.tflite');

    ImageProcessor imageProcessor = ImageProcessorBuilder()
        .add(ResizeOp(320, 320, ResizeMethod.NEAREST_NEIGHBOUR))
        .build();
   TensorImage tensorImage = TensorImage.fromFile(File('images/input.jpg'));
   tensorImage = imageProcessor.process(tensorImage);

   // I presume that at this step the image is resized to the right shape,
   // though I also experimented with manual apriori resizing, just to make
   // sure the issue is not at this stage
   // Image imgIn = decodeJpg(File('images/input.jpg').readAsBytesSync());
   // Image imgResized = copyResize(imgIn, width: 320, height: 320);
   // TensorImage tensorImage = TensorImage.fromImage(imgResized);


    TensorBuffer outputBuffer = TensorBuffer.createFixedSize(
        interpreter.getOutputTensor(0).shape,
        interpreter.getOutputTensor(0).type);

    interpreter.run(tensorImage.buffer, outputBuffer);

When run is invoked I get high CPU use for a few minutes (running this in an Android Emulator), and then the program crashes with the error above. Running it on an actual smartphone yields the same results.

Running the original model with PyTorch takes less than a second on the same hardware, so I am sure this is not inherent complexity in the model (especially that the tflite version is simplified, so it should probably be faster).

How can I understand the root cause of this problem and address it?

Different shape of input (1, C, H, W)

Hi, my tflite model converted from Pytorch has input shape [1, C, H, W]. But TensorImage always gives me a tensor with shape [H, W, C]. I just gave up on reading source code. Please could you give me a clue on how to moveaxis or another solution to this case?

InputTensor of model has shape [1, 3, 240, 240] .
OutputTensor has shape [1,1].
Its regression task.

Flutter 3.0 error

I think this is a new error after upgrading to flutter 3.0. when i downgrade to flutter 2.10.5 the error goes away. is this new request permissions something new in flutter 3?

`

Flutter 3.0.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision ee4e09cce0 (7 days ago) • 2022-05-09 16:45:18 -0700
Engine • revision d1b9a6938a
Tools • Dart 2.17.0 • DevTools 2.12.2

Running flutter doctor...
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.0.0, on Microsoft Windows [Version 10.0.19044.1706], locale en-US)
X cmdline-tools component is missing
Run path/to/sdkmanager --install "cmdline-tools;latest"
See https://developer.android.com/studio/command-line for more details.
X Android license status unknown.
Run flutter doctor --android-licenses to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.
[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.11.14)
[√] Android Studio (version 2021.1)
[√] VS Code (version 1.67.1)
[√] Connected device (3 available)
[√] HTTP Host Availability

! Doctor found issues in 1 category.
PS C:\Users\sirca\OneDrive\Documents\GitHub\tw_food2> flutter run -d emulator-5554
No supported devices found with name or id matching 'emulator-5554'.

The following devices were found:
Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19044.1706]
Chrome (web) • chrome • web-javascript • Google Chrome 101.0.4951.54
PS C:\Users\sirca\OneDrive\Documents\GitHub\tw_food2> flutter run -d emulator-5554
Using hardware rendering with device sdk gphone64 x86 64. If you notice graphics artifacts, consider enabling software rendering with
"--enable-software-rendering".
Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
e: C:\Users\sirca\Downloads\flutter_windows_2.10.5-stable\flutter.pub-cache\hosted\pub.dartlang.org\tflite_flutter_helper-0.3.1\android\src\main\kotlin\com\tfliteflutter\tflite_flutter_helper\TfliteFlutterHelperPlugin.kt: (43, 1): Class 'TfliteFlutterHelperPlugin' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult(p0: Int, p1: Array<(out) String!>, p2: IntArray): Boolean defined in io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
e: C:\Users\sirca\Downloads\flutter_windows_2.10.5-stable\flutter.pub-cache\hosted\pub.dartlang.org\tflite_flutter_helper-0.3.1\android\src\main\kotlin\com\tfliteflutter\tflite_flutter_helper\TfliteFlutterHelperPlugin.kt: (143, 2): 'onRequestPermissionsResult' overrides nothing

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':tflite_flutter_helper:compileDebugKotlin'.

Compilation error. See log for more details

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full
    insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 8s
Running Gradle task 'assembleDebug'... 8.8s
Exception: Gradle task assembleDebug failed with exit code 1`

[FEATURE?] Obtaining Image from TensorImage

First of all, thanks for a great work - this library seems really promising.

I have been wondering, would it be possible somehow to obtain image from a TensorImage used for the recognition? Eg. for purposes of storing it or showing with the results after recognition completes. When I call TensorImage.image, I am hitting

StateError(
          "TensorImage is holding a float-value image which is not able to convert a Image.");

Also, ImageConversion class and it methods cannot handle float32 buffer conversion back to Image.

In general, is there currently any way to obtain processed image from TensorImage back as Image or do you plan to add such a feature?

squeeze TensorBuffer

Hi,
I'm tring to test on my model to encode an image. I got a [1, 400, 400 3] tensorBuffer ("hidden_img" below) after forwarding but I want to squeeze the tensor to [400, 400, 3] before calling TensorImage.fromTensorBuffer( tensorBuffer ). Is there any method to squeeze tensorBuffer like squeeze in numpy. Any suggestions would be appreciated!

  TensorImage encode(TensorImage image, List<double> secret) {
    print("success enter encode! ");

    /// Iutputs List
    var inputs = [image.buffer, secret];

    /// Outputs buffer
    TensorBuffer out_secret = TensorBufferFloat(_outputShapes[0]);
    TensorBuffer hidden_img = TensorBufferFloat(_outputShapes[1]);
    TensorBuffer residual = TensorBufferFloat(_outputShapes[2]);

    /// Outputs map
    Map<int, Object> outputs = {
      0: out_secret.buffer,
      1: hidden_img.buffer,
      2: residual.buffer,
    };
    print(_inputShapes.toString());

    /// run
    _interpreter.runForMultipleInputs(inputs, outputs);

    print("run success!");
    // List<int> shapes = [400, 400, 3];
    // hidden_img.resize(shapes);

    return processOutputImage(TensorImage.fromTensorBuffer(hidden_img));
  }

  TensorImage processOutputImage(TensorImage image) {
    //resize and normalize image
    imageProcessor =
        ImageProcessorBuilder().add(NormalizeOp(0, 1 / 255)).build();
    // add();
    //process image one by one
    TensorImage output_image = imageProcessor.process(image);
    return output_image;
  }

iOS flutter run error

I made everything in read me but when I try to flutter run it gives this error. But when I try to run in xcode there are no any error. My app working perfectly. What can I do ? What is the different of flutter run & xcode run

flutter version: latest stable
package version: latest stable

    ** BUILD FAILED **
Xcode's output:
↳
ld: building for iOS Simulator, but linking in object file built for iOS, file '/Users/cagrialtay/development/flutter/.pub-cache/hosted/pub.dartlang.org/tflite_flutter-0.9.0/ios/TensorFlowLiteC.framework/TensorFlowLiteC' for architecture arm64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'OrderedSet' from project 'Pods')
    warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'FMDB' from project 'Pods')
Could not build the application for the simulator.
Error launching application on iPhone 12 Pro Max.

Support for Flutter 2.0

We are trying to use the tflite_flutter package and for the image processor, we would need tflite_flutter_helper.

But when we try to add this dependency in the flutter project, it depends on an older tflite_flutter version.

The latest tflite_flutter version is 0.6.0 and the helper package depends on 0.5.0.

Can the helper package be updated to depend on the latest tflite_flutter version?

If it would be updated then what would the ETA?

Add function to perform transpose operation

I'm working on a model that needs to apply transpose as a step in pre-processing. Can this be done with this library now? if not do you plan to add this feature soon? And If not, I want to implement my own , some pointers will be very much appreciated.

[FEATURE] Extract multiple crops from one image

Hello @am15h ,

First of all, thanks for your quality that's really awesome !

I need to preprocess an image such as I can extract multiple crops from it and stack them into a new axis with TensorImage/TensorBuffer. Thus the output shape for an input image will be ( crops_number, patch_height, patch_width, channels )

However the only function with imageProcessor that can crop an image ( ResizeWithCropOrPadOp(cropSize, cropSize) ) can only do one crop.

To do so, we can imagine a new processing function with the following definition:
ExtractCropsAndStack(cropsPosition, cropHeight, cropWidth) -> TensorImage

where

  • cropsPosition is a List<List<int>> of coordinates of the top-left position of each crop. (ex: [[0,0], [0,100], [100,0], [100, 100]])
  • cropHeight is a int that specify the crop height in pixel (ex: 100)
  • cropWidth is a int that specify the crop width in pixel (ex: 100)

So, if I want to extract 4 crops of a 200x200 image I can set cropsPosition=[[0,0], [0,100], [100,0], [100, 100]], cropHeight = 100 and cropWidth = 100 to get a TensorImage of shape (4, 100, 100, 3).
In such way with a variable number of parametrizable crop position, we can do other crops that centered ones, even if we only need one crop.

So here is the discussion about how to do realize such function and . Is creating a new function into image/ops/ the best way to do or it would be easier if ResizeWithCropOrPadOp can take crops parameters as arguments ?
Let me know if you would be interested to add this feature and how I can contribute to. If the discussion comes to a nice solution, I will be happy to create a branch for it and open a pull request.

Issue while debugging.

Issue shows,

[ +7 ms] e:
C:\Users\jagal\Documents\flutter.pub-cache\hosted\pub.dartlang.org\tflite_flutter_helper-0.3.1\android
src\main\kotlin\com\tfliteflutter\tflite_flutter_helper\TfliteFlutterHelperPlugin.kt: (143, 73): One
type argument expected for class Array
[ +85 ms] FAILURE: Build failed with an exception.
[ +2 ms] * What went wrong:
[ +1 ms] Execution failed for task ':tflite_flutter_helper:compileDebugKotlin'.
[ ] > Compilation error. See log for more details
[ +1 ms] * Try:
[ ] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get
more log output. Run with --scan to get full insights.


TfliterFlutterHelperPlugin.kt (143) :

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray): Boolean {
when (requestCode) {
AUDIO_RECORD_PERMISSION_CODE -> {
if (grantResults != null) {
permissionToRecordAudio = grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
}
completeInitializeRecorder()
return true
}
}
return false
}

Bad state: failed precondition with TensorFlow Lite v3

I am using TensorFlow Lite v3. But I can not run app.
Message error:
Bad state: failed precondition
E/flutter (30067): #0 checkState (package:quiver/check.dart:74:5)
E/flutter (30067): #1 Tensor.setTo (package:tflite_flutter/src/tensor.dart:146:5)
E/flutter (30067): #2 Interpreter.runForMultipleInputs (package:tflite_flutter/src/interpreter.dart:186:33)
E/flutter (30067): #3 Classifier.predict (package:almond/tflite/classifier.dart:151:19)
E/flutter (30067): #4 IsolateUtils.entryPoint (package:almond/utils/isolate_utils.dart:46:54)

My TensorFlow Lite v3 on netron.app view
image

Get exception in interpreter.run

I encounter Unhandled Exception: RangeError (index): Index out of range: index should be less than 4: 4
when execute interpreter.run
Is there any advice ?

Cannot find an axis to label. A valid axis to label should have size larger than 1.

I'm trying to set up my custom hotdog classifier using this library. I have transformed my model to a tflite model and extracted labels [hotdog, nothotdog]. I am able to confirm my input shape is [1, 300, 300, 3] and my output [1, 1]. When I chose the image to predict I'm getting the error:

E/flutter ( 5277): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Invalid argument(s): Cannot find an axis to label. A valid axis to label should have size larger than 1.
E/flutter ( 5277): #0      TensorLabel.getFirstAxisWithSizeGreaterThanOne (package:tflite_flutter_helper/src/label/tensor_label.dart:173:5)
E/flutter ( 5277): #1      new TensorLabel.fromList (package:tflite_flutter_helper/src/label/tensor_label.dart:81:18)
E/flutter ( 5277): #2      Classifier.predict (package:hotdog_classifier/classifier.dart:106:51)
E/flutter ( 5277): #3      _MyHomePageState._predict (package:hotdog_classifier/main.dart:68:28)
E/flutter ( 5277): #4      _MyHomePageState.getImage.<anonymous closure> (package:hotdog_classifier/main.dart:62:7)
E/flutter ( 5277): #5      State.setState (package:flutter/src/widgets/framework.dart:1109:30)
E/flutter ( 5277): #6      _MyHomePageState.getImage (package:hotdog_classifier/main.dart:58:5)

There isn't much documentation to show users how to use their own models for classification. But is anyone able to help me with my issue?

How to get back Image File from Tensor Image

I am not sure if this is the right Platform to ask, but can you please tell me how can I convert the File I get from ImagePicker into a format that is accepted by the Quantized MobileNet Tflite Model.
I run into this error when I send the File directly : "Cannot convert between a TensorFlowLite tensor with type UINT8 and a Java object of type [[F (which is compatible with the TensorFlowLite type FLOAT32)" and my App crashes.
So I decided to use the tflite_flutter_helper to Preprocess the Image I get from gallery before sending it to the Tflite Model, but I dont know how to do it properly.
The Tflite docs suggest that this is the required Input Format : "ByteBuffer sized 224 x 224 x 3 x PIXEL_DEPTH, where PIXEL_DEPTH is 4 for float model, and 1 for quantized model"

This is my code snippet : [https://gist.github.com/SatyamX64/0e4e4bd9898503df05431134a5953403]

preNormalize question

Hi, I got this plugin work but its result is different from the Android version. I guess my configuration is wrong. Sorry, I am newbie to tensorflow.

InputSensorShape: 1,224,224,3
OutputType: float32

@override
NormalizeOp get preProcessNormalizeOp => NormalizeOp(127.5, 127.5);

@override
NormalizeOp get postProcessNormalizeOp => NormalizeOp(0, 1);

Here's the original Android config:

    private val IMAGE_MEAN = 0
    private val IMAGE_STD = 255.0f
    private val MAX_RESULTS = 3
    private val THRESHOLD = 0.4f

Audio classification example: "Unable to destroy activity" error

In the audio classification example app, there is an error that happens when attempting to shut down the app:

D/AndroidRuntime(22879): Shutting down VM
E/AndroidRuntime(22879): FATAL EXCEPTION: main
E/AndroidRuntime(22879): Process: com.example.audio_classification, PID: 22879
E/AndroidRuntime(22879): java.lang.RuntimeException: Unable to destroy activity {com.example.audio_classification/com.example.audio_classification.MainActivity}: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter recorder
E/AndroidRuntime(22879): 	at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5675)
E/AndroidRuntime(22879): 	at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5720)
E/AndroidRuntime(22879): 	at android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:44)
E/AndroidRuntime(22879): 	at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
E/AndroidRuntime(22879): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
E/AndroidRuntime(22879): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325)
E/AndroidRuntime(22879): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(22879): 	at android.os.Looper.loop(Looper.java:246)
E/AndroidRuntime(22879): 	at android.app.ActivityThread.main(ActivityThread.java:8633)
E/AndroidRuntime(22879): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(22879): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
E/AndroidRuntime(22879): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
E/AndroidRuntime(22879): Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter recorder
E/AndroidRuntime(22879): 	at com.tfliteflutter.tflite_flutter_helper.TfliteFlutterHelperPlugin$createRecordListener$1.onMarkerReached(Unknown Source:2)
E/AndroidRuntime(22879): 	at com.tfliteflutter.tflite_flutter_helper.TfliteFlutterHelperPlugin.onDetachedFromEngine(TfliteFlutterHelperPlugin.kt:94)
E/AndroidRuntime(22879): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.remove(FlutterEngineConnectionRegistry.java:262)
E/AndroidRuntime(22879): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.remove(FlutterEngineConnectionRegistry.java:270)
E/AndroidRuntime(22879): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.removeAll(FlutterEngineConnectionRegistry.java:278)
E/AndroidRuntime(22879): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.destroy(FlutterEngineConnectionRegistry.java:122)
E/AndroidRuntime(22879): 	at io.flutter.embedding.engine.FlutterEngine.destroy(FlutterEngine.java:416)
E/AndroidRuntime(22879): 	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onDetach(FlutterActivityAndFragmentDelegate.java:648)
E/AndroidRuntime(22879): 	at io.flutter.embedding.android.FlutterActivity.release(FlutterActivity.java:622)
E/AndroidRuntime(22879): 	at io.flutter.embedding.android.FlutterActivity.onDestroy(FlutterActivity.java:643)
E/AndroidRuntime(22879): 	at android.app.Activity.performDestroy(Activity.java:8468)
E/AndroidRuntime(22879): 	at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1344)
E/AndroidRuntime(22879): 	at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5660)
E/AndroidRuntime(22879): 	... 11 more

This results in Android constantly notifying the user that that "audio_classification keeps stopping".
To reproduce, just launch the app and close it normally with the back button a few times in a row.

Model doesnt work with the plugin

Hi, we are trying to use our tflite model and labels. But it's not detecting the objects. Am new to this. Any help would be greatly appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.