am15h / tflite_flutter_plugin

TensorFlow Lite Flutter Plugin
https://pub.dev/packages/tflite_flutter
Apache License 2.0
504 stars 353 forks source link

Error in model prediction #238

Open DarshanDayal123 opened 1 year ago

DarshanDayal123 commented 1 year ago

import 'dart:io';

import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path_provider/path_provider.dart'; import 'package:tflite_flutter/tflite_flutter.dart';

void main() { runApp(const MyApp()); }

class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);

@override Widget build(BuildContext context) { return MaterialApp( title: 'Cat or Dog', theme: ThemeData( primarySwatch: Colors.blue, ), home: SplashPage(), ); } }

class SplashPage extends StatefulWidget { @override _SplashPageState createState() => _SplashPageState(); }

class _SplashPageState extends State { File? _imageFile; late Interpreter _interpreter; late List _labels; bool _isLoaded = false; bool _isImagePickerActive = false; // Flag to track image picker activity

@override void initState() { super.initState(); loadModel().then((_) { setState(() { _isLoaded = true; }); }); }

Future loadModel() async { _interpreter = await Interpreter.fromAsset('assets/model.tflite'); _labels = await loadLabels('assets/labels.txt'); }

Future<List> loadLabels(String path) async { String labelData = await rootBundle.loadString(path); return labelData.trim().split('\n'); }

Future classifyImage(File imageFile) async { if (!_isLoaded) return;

var inputImage = await imageFile.readAsBytes();
var output = List.filled(_labels.length, 0).reshape([1, _labels.length]);

_interpreter.run(inputImage, output);

var predictionIndex = output[0].indexOf(output[0].reduce((a, b) => a > b ? a : b));
var predictionLabel = predictionIndex == 0 ? 'Dog' : 'Cat';

showDialog(
  context: context,
  builder: (context) => AlertDialog(
    title: Text('Prediction'),
    content: Text('The image is classified as $predictionLabel.'),
    actions: [
      TextButton(
        onPressed: () => Navigator.pop(context),
        child: Text('OK'),
      ),
    ],
  ),
);

}

Future selectImage() async { if (_isImagePickerActive) return; // Check if image picker is already active _isImagePickerActive = true; // Set the flag to true

var pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery);
_isImagePickerActive = false; // Reset the flag

if (pickedImage == null) return;

setState(() {
  _imageFile = File(pickedImage.path);
});

classifyImage(_imageFile!);

}

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Cat or Dog'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_imageFile != null) Image.file( _imageFile!, height: 200, ), SizedBox(height: 20), ElevatedButton( onPressed: selectImage, child: Text('Select Image'), ), ], ), ), ); } }

output its take image but don't predict that this is cat or dog error got on console Unable to match the desired swap behavior. E/flutter (29351): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: failed precondition