classifyImage method
- File imageFile
Classifies a mosquito image and returns the predicted species and confidence.
This method performs the core classification operation by processing an image through the loaded PyTorch model. It handles image preprocessing, model inference, and result post-processing to return a clean prediction.
Image Processing Pipeline
- Image Loading: Reads image bytes from the provided file
- Preprocessing: Resizes to 224x224 and applies ImageNet normalization
- Model Inference: Runs the image through the neural network
- Post-processing: Applies softmax and extracts top prediction
- Result Formatting: Returns scientific name and confidence score
Input Requirements
- Supported Formats: JPEG, PNG, BMP, WebP
- Recommended Size: Any size (automatically resized to 224x224)
- Color Space: RGB (grayscale images are converted)
- File Size: No strict limit, but larger files take longer to process
Output Format
Returns a map with the following keys:
'scientificName': String containing the predicted species name'confidence': Double between 0.0 and 1.0 representing prediction confidence
Performance Characteristics
- Inference Time: Typically 100-2000ms depending on device
- Memory Usage: ~50-100MB during inference
- CPU Usage: High during inference, minimal when idle
Error Conditions
- Throws Exception if the model is not loaded (call loadModel first)
- Throws Exception if the image file cannot be read
- Throws Exception if the image format is not supported
- Throws Exception if insufficient memory is available
Example:
final imageFile = File('/path/to/mosquito.jpg');
try {
final result = await classificationService.classifyImage(imageFile);
final species = result['scientificName'] as String;
final confidence = result['confidence'] as double;
print('Predicted species: $species');
print('Confidence: ${(confidence * 100).toStringAsFixed(1)}%');
} catch (e) {
print('Classification failed: $e');
}
See also:
- loadModel which must be called before using this method
- ClassificationResult for the enriched result format used by repositories
Implementation
Future<Map<String, dynamic>> classifyImage(File imageFile) async {
if (_model == null) {
throw Exception("Model not loaded - call loadModel() first");
}
final imageBytes = await imageFile.readAsBytes();
// This returns a map like {'label': 'Aedes aegypti', 'probability': 0.98}
final result = await _model!.getImagePredictionResult(imageBytes);
print(result['label']);
print("[DEBUG] Raw name length: ${result['label'].length}");
// Return the raw prediction directly with cleaned scientific name
return {
'scientificName': result['label'].trim(),
'confidence': result['probability'],
};
}