Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
rsAnDT opened this issue Nov 1, 2024 · 3 comments

Comments

@rsAnDT
Copy link

rsAnDT commented Nov 1, 2024

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 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 !

@yAlqubati
Copy link

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

@wonderkidshihab
Copy link

Facing the same issue

@yAlqubati
Copy link

yAlqubati commented Jan 5, 2025

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]);
  }`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants