我正在尝试制作一个应用程序游乐场,将照片分类为苹果或橙色。我有一个名为“AppleOrange.mlmodel”的模型文件,它是为此训练的。但是我无法加载模型文件。
我的代码:
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 ""
}