Created
January 16, 2020 15:07
-
-
Save AbhishekDoshi26/df9014c3ed5ad533b10f1011fa2a047c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:flutter/material.dart'; | |
import 'package:image_picker/image_picker.dart'; | |
import 'package:tflite/tflite.dart'; | |
void main() => runApp(MaterialApp( | |
home: MyApp(), | |
)); | |
class MyApp extends StatefulWidget { | |
@override | |
_MyAppState createState() => _MyAppState(); | |
} | |
class _MyAppState extends State<MyApp> { | |
List _outputs; | |
File _image; | |
bool _loading = false; | |
@override | |
void initState() { | |
super.initState(); | |
_loading = true; | |
loadModel().then((value) { | |
setState(() { | |
_loading = false; | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
resizeToAvoidBottomInset: false, | |
resizeToAvoidBottomPadding: false, | |
appBar: AppBar( | |
title: const Text('Teachable Machine Learning'), | |
), | |
body: _loading | |
? Container( | |
alignment: Alignment.center, | |
child: CircularProgressIndicator(), | |
) | |
: Container( | |
width: MediaQuery.of(context).size.width, | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.center, | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
_image == null ? Container() : Image.file(_image), | |
SizedBox( | |
height: 20, | |
), | |
_outputs != null | |
? Text( | |
"${_outputs[0]["label"]}", | |
style: TextStyle( | |
color: Colors.black, | |
fontSize: 20.0, | |
background: Paint()..color = Colors.white, | |
), | |
) | |
: Container() | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: pickImage, | |
child: Icon(Icons.image), | |
), | |
); | |
} | |
pickImage() async { | |
var image = await ImagePicker.pickImage(source: ImageSource.camera); | |
if (image == null) return null; | |
setState(() { | |
_loading = true; | |
_image = image; | |
}); | |
classifyImage(image); | |
} | |
classifyImage(File image) async { | |
var output = await Tflite.runModelOnImage( | |
path: image.path, | |
numResults: 6, | |
threshold: 0.5, | |
imageMean: 127.5, | |
imageStd: 127.5, | |
); | |
setState(() { | |
_loading = false; | |
_outputs = output; | |
}); | |
} | |
loadModel() async { | |
await Tflite.loadModel( | |
model: "assets/model_unquant.tflite", | |
labels: "assets/labels.txt", | |
); | |
} | |
@override | |
void dispose() { | |
Tflite.close(); | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment