Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save apple-avadhesh/8aed6948bd03e23ccacf078e5d41c22a to your computer and use it in GitHub Desktop.
Save apple-avadhesh/8aed6948bd03e23ccacf078e5d41c22a to your computer and use it in GitHub Desktop.
Simple text recognition using Apple's Vision Framework (Part 3)
import UIKit
import Vision
let image = UIImage(named: "<image_name_goes_here>")
if let cgImage = image?.cgImage {
let requestHandler = VNImageRequestHandler(cgImage: cgImage)
let recognizeTextRequest = VNRecognizeTextRequest { (request, error) in
// 1. Parse the results
guard let observations = request.results as? [VNRecognizedTextObservation] else {
return
}
// 2. Extract the data you want
let recognizedStrings = observations.compactMap { observation in
observation.topCandidates(1).first?.string
}
// 3. Display or update UI
DispatchQueue.main.async {
print(recognizedStrings)
}
}
recognizeTextRequest.recognitionLevel = .fast
DispatchQueue.global(qos: .userInitiated).async {
do {
try requestHandler.perform([recognizeTextRequest])
} catch {
print(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment