yolo_service.dart 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'dart:typed_data';
  2. import 'dart:io';
  3. import 'package:image_picker/image_picker.dart';
  4. import 'package:ultralytics_yolo/ultralytics_yolo.dart';
  5. class YoloService {
  6. late YOLO _yolo;
  7. final ImagePicker _picker = ImagePicker();
  8. bool _isInitialized = false;
  9. Future<void> initModel() async {
  10. try {
  11. _yolo = YOLO(
  12. modelPath: 'best.tflite',
  13. task: YOLOTask.detect,
  14. useGpu: false, // Disabling GPU for better stability on budget devices
  15. );
  16. final success = await _yolo.loadModel();
  17. if (!success) {
  18. throw Exception("Model failed to load.");
  19. }
  20. _isInitialized = true;
  21. } catch (e) {
  22. print("YOLO Init Error: $e");
  23. rethrow;
  24. }
  25. }
  26. Future<XFile?> pickImage() async {
  27. return await _picker.pickImage(
  28. source: ImageSource.gallery,
  29. maxWidth: 640,
  30. maxHeight: 640,
  31. );
  32. }
  33. Future<List<dynamic>?> runInference(String imagePath) async {
  34. if (!_isInitialized) {
  35. await initModel();
  36. }
  37. try {
  38. final File imageFile = File(imagePath);
  39. final Uint8List bytes = await imageFile.readAsBytes();
  40. final results = await _yolo.predict(bytes);
  41. return results['detections'] as List<dynamic>?;
  42. } catch (e) {
  43. print("YOLO Inference Error: $e");
  44. rethrow;
  45. }
  46. }
  47. void dispose() {
  48. // No explicit close on YOLO class
  49. }
  50. }