predict method
Runs inference on a single image.
Takes raw image bytes as input and returns a map containing the inference results. The structure of the returned map depends on the task type:
- For detection: Contains 'boxes' with class, confidence, and bounding box coordinates.
- For segmentation: Contains 'boxes' with class, confidence, bounding box coordinates, and mask data.
- For classification: Contains class and confidence information.
- For pose estimation: Contains keypoints information for detected poses.
- For OBB: Contains oriented bounding box coordinates.
The model must be loaded with loadModel before calling this method.
Example:
final results = await yolo.predict(imageBytes);
final boxes = results['boxes'] as List<Map<String, dynamic>>;
for (var box in boxes) {
print('Class: ${box['class']}, Confidence: ${box['confidence']}');
}
Returns a map containing the inference results. If inference fails, throws an exception.
@param imageBytes The raw image data as a Uint8List @return A map containing the inference results @throws ModelNotLoadedException if the model has not been loaded @throws InferenceException if there's an error during inference @throws PlatformException if there's an issue with the platform-specific code
Implementation
Future<Map<String, dynamic>> predict(Uint8List imageBytes) async {
if (imageBytes.isEmpty) {
throw InvalidInputException('Image data is empty');
}
try {
final result = await _channel.invokeMethod('predictSingleImage', {
'image': imageBytes,
});
if (result is Map) {
// Convert Map<Object?, Object?> to Map<String, dynamic>
Map<String, dynamic> resultMap = Map<String, dynamic>.fromEntries(
result.entries.map((e) => MapEntry(e.key.toString(), e.value))
);
// Convert boxes list if it exists
if (resultMap.containsKey('boxes') && resultMap['boxes'] is List) {
List<Map<String, dynamic>> boxes = (resultMap['boxes'] as List).map((item) {
if (item is Map) {
return Map<String, dynamic>.fromEntries(
item.entries.map((e) => MapEntry(e.key.toString(), e.value))
);
}
return <String, dynamic>{};
}).toList();
resultMap['boxes'] = boxes;
}
return resultMap;
}
throw InferenceException('Invalid result format returned from inference');
} on PlatformException catch (e) {
if (e.code == 'MODEL_NOT_LOADED') {
throw ModelNotLoadedException('Model has not been loaded. Call loadModel() first.');
} else if (e.code == 'INVALID_IMAGE') {
throw InvalidInputException('Invalid image format or corrupted image data');
} else if (e.code == 'INFERENCE_ERROR') {
throw InferenceException('Error during inference: ${e.message}');
} else {
throw InferenceException('Platform error during inference: ${e.message}');
}
} catch (e) {
throw InferenceException('Unknown error during inference: $e');
}
}