Skip to content

Instantly share code, notes, and snippets.

@bourdakos1
Created June 24, 2017 19:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bourdakos1/e9c6159d9247646f2292ea09bc0c575b to your computer and use it in GitHub Desktop.
Save bourdakos1/e9c6159d9247646f2292ea09bc0c575b to your computer and use it in GitHub Desktop.
// Classification method.
func classify(_ image: CGImage, completion: @escaping ([VNClassificationObservation]) -> Void) {
DispatchQueue.global(qos: .background).async {
// Initialize the coreML vision model, you can also use VGG16().model, or any other model that takes an image.
guard let vnCoreModel = try? VNCoreMLModel(for: Inceptionv3().model) else { return }
// Build the coreML vision request.
let request = VNCoreMLRequest(model: vnCoreModel) { (request, error) in
// We get get an array of VNClassificationObservations back
// This has the fields "confidence", which is the score
// and "identifier" which is the recognized class
guard var results = request.results as? [VNClassificationObservation] else { fatalError("Failure") }
// Filter out low scoring results.
results = results.filter({ $0.confidence > 0.01 })
DispatchQueue.main.async {
completion(results)
}
}
// Initialize the coreML vision request handler.
let handler = VNImageRequestHandler(cgImage: image)
// Perform the coreML vision request.
do {
try handler.perform([request])
} catch {
print("Error: \(error)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment