| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import 'dart:typed_data';
- import 'dart:io';
- import 'package:image_picker/image_picker.dart';
- import 'package:ultralytics_yolo/ultralytics_yolo.dart';
- class YoloService {
- late YOLO _yolo;
- final ImagePicker _picker = ImagePicker();
- bool _isInitialized = false;
- Future<void> initModel() async {
- try {
- _yolo = YOLO(
- modelPath: 'best.tflite',
- task: YOLOTask.detect,
- useGpu: false, // Disabling GPU for better stability on budget devices
- );
- final success = await _yolo.loadModel();
- if (!success) {
- throw Exception("Model failed to load.");
- }
- _isInitialized = true;
- } catch (e) {
- print("YOLO Init Error: $e");
- rethrow;
- }
- }
- Future<XFile?> pickImage() async {
- return await _picker.pickImage(
- source: ImageSource.gallery,
- maxWidth: 640,
- maxHeight: 640,
- );
- }
- Future<List<dynamic>?> runInference(String imagePath) async {
- if (!_isInitialized) {
- await initModel();
- }
-
- try {
- final File imageFile = File(imagePath);
- final Uint8List bytes = await imageFile.readAsBytes();
- final results = await _yolo.predict(bytes);
- return results['detections'] as List<dynamic>?;
- } catch (e) {
- print("YOLO Inference Error: $e");
- rethrow;
- }
- }
- void dispose() {
- // No explicit close on YOLO class
- }
- }
|