I am trying to make an app playground that will classify a photo as Apple or Orange. I have a model file called "AppleOrange.mlmodel" that is trained for this. But I cannot load the model file.
My code:
func classifyImage(imageName: String, modelName: String) -> String {
guard let modelPath = Bundle.main.path(forResource: modelName, ofType: "mlmodel") else {
return "Error: Could not find model."
}
let modelURL = URL(fileURLWithPath: modelPath)
guard let model = try? VNCoreMLModel(for: MLModel(contentsOf: modelURL)) else {
return "Error: Could not load model."
}
guard let image = UIImage(named: imageName)?.cgImage else {
return "Error: Could not load image."
}
let request = VNCoreMLRequest(model: model) {
[self] (request, error) in
guard let results = request.results as? [VNClassificationObservation], let topResult = results.first else {
return
}
let confidence = topResult.confidence * 100
let fruit = topResult.identifier
DispatchQueue.main.async {
self.classificationResult = "This is a \(fruit) with \(String(format: "%.2f", confidence))% confidence."
}
}
let handler = VNImageRequestHandler(cgImage: image)
try? handler.perform([request])
return ""
}