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 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 pickImage() async { return await _picker.pickImage( source: ImageSource.gallery, maxWidth: 640, maxHeight: 640, ); } Future?> 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?; } catch (e) { print("YOLO Inference Error: $e"); rethrow; } } void dispose() { // No explicit close on YOLO class } }