getImagePredictionResult method

Future<Map<String, dynamic>> getImagePredictionResult(
  1. Uint8List imageAsBytes, {
  2. List<double> mean = TORCHVISION_NORM_MEAN_RGB,
  3. List<double> std = TORCHVISION_NORM_STD_RGB,
})

Runs image classification and returns label with confidence.

Processes the image through the model and returns both the predicted label and its confidence probability.

@param imageAsBytes The raw image bytes @param mean Optional normalization mean values (default: ImageNet means) @param std Optional normalization std values (default: ImageNet stds) @return A Future that completes with a map containing 'label' and 'probability' keys

Implementation

Future<Map<String, dynamic>> getImagePredictionResult(Uint8List imageAsBytes,
    {List<double> mean = TORCHVISION_NORM_MEAN_RGB,
    List<double> std = TORCHVISION_NORM_STD_RGB}) async {
  // Assert mean std
  assert(mean.length == 3, "mean should have size of 3");
  assert(std.length == 3, "std should have size of 3");

  final List<double?> prediction = await ModelApi().getImagePredictionList(
      _index, imageAsBytes, null, null, null, mean, std);

  // Get the index of the max score
  int maxScoreIndex = 0;
  for (int i = 1; i < prediction.length; i++) {
    if (prediction[i]! > prediction[maxScoreIndex]!) {
      maxScoreIndex = i;
    }
  }

  //Getting sum of exp
  double sumExp = 0.0;
  for (var element in prediction) {
    sumExp = sumExp + math.exp(element!);
  }

  final predictionProbabilities =
      prediction.map((element) => math.exp(element!) / sumExp).toList();

  return {
    "label": labels[maxScoreIndex],
    "probability": predictionProbabilities[maxScoreIndex]
  };
}