flutter-tflite icon indicating copy to clipboard operation
flutter-tflite copied to clipboard

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: failed precondition

Open rsAnDT opened this issue 1 year ago • 5 comments
trafficstars

import 'dart:io'; import 'dart:typed_data'; import 'package:image/image.dart' as img; import 'package:tflite_flutter/tflite_flutter.dart'; import 'package:tflite_flutter_helper/tflite_flutter_helper.dart';

class AgeEstimationModel { static const int inputImageSize = 200; static const double p = 116; late Interpreter _interpreter; late ImageProcessor _imageProcessor;

int inferenceTime = 0;

static Future<AgeEstimationModel> create() async { var model = AgeEstimationModel._(); await model._loadModel(); return model; }

AgeEstimationModel._() { _imageProcessor = ImageProcessorBuilder() .add(ResizeOp(inputImageSize, inputImageSize, ResizeMethod.BILINEAR)) .add(NormalizeOp(0.0, 1.0)) .build(); }

Future _loadModel() async { try { _interpreter = await Interpreter.fromAsset('model_lite_age_q.tflite'); print('Model loaded successfully'); } catch (e) { print('Error loading model: $e'); } }

Future predictAge(File imageFile) async { if (_interpreter == null) { throw StateError('Interpreter has not been initialized'); }

final start = DateTime.now();
final imageBytes = await imageFile.readAsBytes();

img.Image? image = img.decodeImage(imageBytes);
if (image == null) {
  throw StateError('Unable to decode image');
}

img.Image rgbImage = img.copyResize(image, width: inputImageSize, height: inputImageSize);

if (rgbImage.numberOfChannels != 3) {
  rgbImage = img.Image.rgb(rgbImage.width, rgbImage.height);
  for (int y = 0; y < rgbImage.height; y++) {
    for (int x = 0; x < rgbImage.width; x++) {
      rgbImage.setPixel(x, y, image.getPixel(x, y));
    }
  }
}

Float32List inputTensor = Float32List(1 * inputImageSize * inputImageSize * 3);

for (int y = 0; y < rgbImage.height; y++) {
  for (int x = 0; x < rgbImage.width; x++) {
    int pixel = rgbImage.getPixel(x, y);
    inputTensor[0 * inputImageSize * inputImageSize * 3 + y * inputImageSize * 3 + x * 3 + 0] = img.getRed(pixel) / 255.0;   // R
    inputTensor[0 * inputImageSize * inputImageSize * 3 + y * inputImageSize * 3 + x * 3 + 1] = img.getGreen(pixel) / 255.0; // G
    inputTensor[0 * inputImageSize * inputImageSize * 3 + y * inputImageSize * 3 + x * 3 + 2] = img.getBlue(pixel) / 255.0;  // B
  }
}

if (inputTensor.length != 1 * inputImageSize * inputImageSize * 3) {
  throw StateError('Size of inputTensor fail: ${inputTensor.length}');
}

var ageOutputArray = List.generate(1, (_) => List.filled(1, 0.0));

print("Input Tensor: $inputTensor");
if (inputTensor.isEmpty || ageOutputArray.isEmpty) {
  throw StateError('Input tensor or output array is empty');
}

print('>>>input shape: ${_interpreter.getInputTensor(0).shape}, type: ${_interpreter.getInputTensor(0).type}');
print('>>>output shape: ${_interpreter.getOutputTensor(0).shape}, type: ${_interpreter.getOutputTensor(0).type}');

_interpreter.run(inputTensor, ageOutputArray);

double predictedAge = ageOutputArray[0][0] * p;
print("Age estimate: $predictedAge");

inferenceTime = DateTime.now().difference(start).inMilliseconds;
print("Inference time: $inferenceTime ms");

return predictedAge;

}

void dispose() { _interpreter.close(); } }

flutter: >>>input shape: [1, 200, 200, 3], type: TfLiteType.float32 flutter: >>>output shape: [1, 1], type: TfLiteType.float32 [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: failed precondition

image: ^3.0.1 tflite_flutter: ^0.9.0 tflite_flutter_helper: ^0.3.1

Please help me, Thanks !

rsAnDT avatar Nov 01 '24 02:11 rsAnDT

I'm facing the same problem, have you found a solution?

yAlqubati avatar Dec 16 '24 17:12 yAlqubati

Facing the same issue

wonderkidshihab avatar Jan 05 '25 14:01 wonderkidshihab

my problem was that i can't find the functions called getRed,getGreen and getBlue, so I use another way to extract the RGB, here is the code


`List<dynamic> imageToArray(img.Image inputImage) {
    List<double> flattenedList = inputImage.data!
        .expand((channel) => [channel.r, channel.g, channel.b])
        .map((value) => value.toDouble() / 255.0) // Normalize to [0, 1]
        .toList();

    Float32List reshapedArray = Float32List(1 * 640 * 640 * 3);
    int index = 0;

    for (int h = 0; h < 640; h++) {
      for (int w = 0; w < 640; w++) {
        reshapedArray[index++] = flattenedList[h * 640 * 3 + w * 3 + 0]; // Red
        reshapedArray[index++] = flattenedList[h * 640 * 3 + w * 3 + 1]; // Green
        reshapedArray[index++] = flattenedList[h * 640 * 3 + w * 3 + 2]; // Blue
      }
    }

    return reshapedArray.reshape([1, 640, 640, 3]);
  }`

yAlqubati avatar Jan 05 '25 14:01 yAlqubati

I am having same issue, anybody please give me advice if you have resolved

cg-tester avatar Jan 27 '25 11:01 cg-tester

i needed to downgrade to image: ^3.1.3

jasonjackson avatar Jan 28 '25 06:01 jasonjackson