Search code examples
androidiosfluttertensorflowdart

Unhandled Exception: PlatformException(Failed to run model, Interpreter busy, java.lang.RuntimeException: Interpreter busy in flutter


I used tflite and imagepicker in my app for using tensorflow lite to differentiate between cat and dog. Now, this exception keeps coming up whenever i pick image from gallery, after picking an image, I should get an output, telling me wheather it's a cat or dog, but i get nothing and return back to previous screen with an exceprion. Please help me out.

Here's the code -

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite/tflite.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  bool _isLoading=true;
  File _image = File("");
  List _output = [];
  final picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    loadModel().then((value) {
      setState(() {

      });
    });
  }

  detectImage(File image) async {
    var output = await Tflite.runModelOnImage(
      path: image.path,
      numResults: 2,
      threshold: 0.6,
      imageMean: 127.5,
      imageStd: 127.5,
    );
    setState(() {
      _output.add(output);
      _isLoading = false;
    });
    output!=null ? output.clear() : null;
  }

  loadModel() async {
    await Tflite.loadModel(
      model: 'assets/model_unquant.tflite',
      labels: 'assets/labels.txt',
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

  }

  pickImage() async {
    var image = await picker.getImage(source: ImageSource.camera);
    if(image == null)
      return null;

    setState(() {
      _image = File(image.path);
    });

    detectImage(_image);
  }

  pickGalleryImage() async {
    var image = await picker.getImage(source: ImageSource.gallery);
    if(image == null)
      return null;

    setState(() {
      _image = File(image.path);
    });

    detectImage(_image);
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.grey[400],
        body: Center(
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 20.0,),
                Center(
                  child: Text(
                    'Cats and Dogs Detector app',
                    style: TextStyle(
                      fontSize: 25.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.white70,
                    ),
                  ),
                ),
                SizedBox(height: 200.0),
                Center(
                  child: _isLoading ? Container(
                    width: MediaQuery.of(context).size.width*0.9,
                    child: Column(
                      children: [
                        Image.asset("assets/cats n dogs 2.jpg", fit: BoxFit.cover,)
                      ],
                    ),
                  ) : Container(
                    child: Column(
                      children: [
                        Container(
                          height: 250,
                          child: Image.file(_image),
                        ),
                        SizedBox(height: 20.0,),
                        _output!=null ? Text('${_output[0]['label']}', style: TextStyle(color: Colors.white, fontSize: 15.0),) : Container(),
                        SizedBox(height: 10.0,),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 20.0,
                ),
                Center(
                  child: Container(
                    width: MediaQuery.of(context).size.width*0.6,
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        ElevatedButton(
                          onPressed: () {
                            pickImage();
                          },
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(Colors.grey),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15.0),
                            child: Text(
                              'Capture a pic',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 17.5,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          height: MediaQuery.of(context).size.height*0.01,
                        ),
                        ElevatedButton(
                          onPressed: () {
                            pickGalleryImage();
                          },
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(Colors.grey),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 15.0),
                            child: Text(
                              'Select from gallery',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 17.50,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Here is the exception -

Performing hot restart...
Syncing files to device sdk gphone x86 arm...
Restarted application in 1,187ms.
E/flutter ( 7687): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(Failed to run model, Interpreter busy, java.lang.RuntimeException: Interpreter busy
E/flutter ( 7687):  at sq.flutter.tflite.TflitePlugin$TfliteTask.<init>(TflitePlugin.java:450)
E/flutter ( 7687):  at sq.flutter.tflite.TflitePlugin$RunModelOnImage.<init>(TflitePlugin.java:488)
E/flutter ( 7687):  at sq.flutter.tflite.TflitePlugin.onMethodCall(TflitePlugin.java:105)
E/flutter ( 7687):  at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/flutter ( 7687):  at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/flutter ( 7687):  at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/flutter ( 7687):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter ( 7687):  at android.os.MessageQueue.next(MessageQueue.java:335)
E/flutter ( 7687):  at android.os.Looper.loop(Looper.java:183)
E/flutter ( 7687):  at android.app.ActivityThread.main(ActivityThread.java:7656)
E/flutter ( 7687):  at java.lang.reflect.Method.invoke(Native Method)
E/flutter ( 7687):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/flutter ( 7687):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
E/flutter ( 7687): , null)
E/flutter ( 7687): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
E/flutter ( 7687): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)
E/flutter ( 7687): <asynchronous suspension>
E/flutter ( 7687): #2      Tflite.runModelOnImage (package:tflite/tflite.dart:34:12)
E/flutter ( 7687): <asynchronous suspension>
E/flutter ( 7687): #3      _HomeState.detectImage (package:dog_cat_classification/home.dart:30:18)
E/flutter ( 7687): <asynchronous suspension>
E/flutter ( 7687): 

Solution

  • Instead of hot reload/hot restart, stop and run the session again.