Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created May 9, 2022 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturdysturge/a9430ba8543c06007d3fe48a7d0028a9 to your computer and use it in GitHub Desktop.
Save sturdysturge/a9430ba8543c06007d3fe48a7d0028a9 to your computer and use it in GitHub Desktop.
import Vision
extension VNClassificationObservation {
var debugString: String {
"""
Confidence: \(String(format: "%.f", confidence * 100))%
Guesses: \(identifier)
"""
}
}
extension VNRequest {
static func fromFile(named name: String,
withExtension extension: String = "mlmodelc",
completion: @escaping (String) -> Void) -> VNRequest {
guard let modelURL = Bundle.main.url(forResource: name, withExtension: "mlmodelc") else {
fatalError("Model file is missing")
}
do {
let visionModel = try VNCoreMLModel(for: MLModel(contentsOf: modelURL))
return VNCoreMLRequest(model: visionModel) { (request, error) in
DispatchQueue.main.async {
if let results = request.results {
guard let topLabelObservation = results.first as?
VNClassificationObservation else {
return
}
completion(topLabelObservation.debugString)
}
}
}
} catch {
fatalError(String(describing: error))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment