Closed billyjuliux closed 1 year ago
It turns out I was passing the wrong params for the input shape, closing this issue.
Hi Everyone, I am making a Maize Plant Disease detection Mobile app using Flutter and deep learning
I have saved my model in Tflite and wrote the following code but getting error: import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:tflite_flutter/tflite_flutter.dart'; import 'dart:io'; import 'package:flutter/services.dart' show rootBundle; import 'package:image/image.dart' as img;
class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); }
class _HomePageState extends State
@override void initState() { super.initState(); loadModel().then((_) { setState(() { _isModelReady = true; print('Model is ready.'); }); }); }
Future
// Initialize the interpreter with the loaded model
_interpreter = await Interpreter.fromBuffer(modelUint8List);
if (_interpreter == null) {
print('Error: Interpreter initialization failed.');
return;
}
// Load the labels.txt from the assets directory
final labelsData = await rootBundle.loadString('lib/ml/labels.txt');
if (labelsData == null) {
print('Error: Labels file not found.');
return;
}
_classLabels = labelsData.split('\n');
print('Model loaded and interpreter initialized successfully.');
} catch (e) {
print('Failed to load model: $e');
}
}
Future
// Run model inference on the picked image
await runModelOnImage();
} catch (e) {
print('Failed to pick and process image: $e');
}
}
Future
// Run model inference
final output = List.filled(_classLabels!.length, 0.0);
_interpreter!.run(inputImage.buffer.asUint8List(), output);
setState(() {
_output = output;
});
print('Model inference successful.');
// Navigate to the display image page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayImagePage(
image: _image!,
output: _output,
classLabels: _classLabels,
),
),
);
} else {
print('Failed to preprocess image: Image is null.');
}
} catch (e) {
print('Failed to run model: $e');
}
} else {
print('Model is not ready or image is null or interpreter is null.');
}
}
@override void dispose() { _interpreter?.close(); super.dispose(); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Image Picker Example'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_image != null) Image.file(_image!), SizedBox(height: 10.0), ElevatedButton( onPressed: () => _pickImage(ImageSource.gallery), child: Text('Pick Image'), ), SizedBox(height: 10.0), ElevatedButton( onPressed: () { if (_isModelReady && _image != null && _interpreter != null) { runModelOnImage(); } else { print( 'Cannot predict. Model, image, or interpreter is not ready.'); } }, child: Text('Predict'), ), ], ), ), ); } }
class DisplayImagePage extends StatelessWidget {
final File image;
final List
const DisplayImagePage({ required this.image, required this.output, required this.classLabels, });
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Image Display'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.file(image), SizedBox(height: 20.0), if (output != null && classLabels != null) Text( 'Predicted Class: ${output != null ? classLabels![output!.indexOf(output!.reduce((a, b) => a > b ? a : b))] : 'Unknown'}', style: TextStyle(fontSize: 18.0), ), ], ), ), ); } }
Error: I/flutter (16401): Failed to run model: Bad state: failed precondition
Please help me to solve this asap
It turns out I was passing the wrong params for the input shape, closing this issue.
hi this happen also from me using custom model could you show me what the input params here
Hi @cahyowhy, I incorrectly passed [width, channel] args to [height, width] params which caused the problem. You can try to use interpreter.getInputTensor
to check your input shape and pass the correct args.
The type of this buffer should be
TfLiteType.float32
and notTfLiteType.uint8
.More info:
This issue occurs because:
You might not be using the input/output buffers of correct shape, type as required by the interpreter. Verify this using
interpreter.getInputTensors()
andinterpreter.getOutputTensors()
Probably the values of input buffer are not the expected ones. Maybe you are forgetting to normalize your input. Try using NormalizeOp.
_Originally posted by @am15h in https://github.com/am15h/tflite_flutter_plugin/issues/29#issuecomment-663587710_
Hi @am15h, I recently ran to this problem (Bad state: failed precondition). I'm trying to use the CRAFT TFLite model. I have ensured the shape and type of the input and output to be the same as what to be expected by the model. I'm guessing the problem lies on the NormalizeOp mean and std values (the second cause on your list, attached above).
I've tried your Image Classification Image and it works fine, using the defined mean and std values of 127.5. How do you calculate or find these NormalizeOp values?
Any help would be appreciated. Thanks in advance.