Skip to content

Instantly share code, notes, and snippets.

@craigmarvelley
Last active August 4, 2023 13:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigmarvelley/a2135c713cd38e17e9f70ffaa7722697 to your computer and use it in GitHub Desktop.
Save craigmarvelley/a2135c713cd38e17e9f70ffaa7722697 to your computer and use it in GitHub Desktop.
private func ocrRequestHandler(request: VNRequest, error: Error?) {
guard let observations = request.results as? [VNRecognizedTextObservation] else { return }
var ocrCandidates: [OCRCandidate] = []
for observation in observations {
guard let topCandidate = observation.topCandidates(1).first else { return }
// Vision algorithms use a coordinate system with lower left origin.
// Converting to upper left so the y values are increasing as the bounding box for observation
// goes down the list as to how humans read english text.
let transform = CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: 0, y: -1)
let boundingPoints = OCRCandidate.BoundingPoints(bottomLeft: observation.bottomLeft.applying(transform),
bottomRight: observation.bottomRight.applying(transform),
topRight: observation.topRight.applying(transform),
topLeft: observation.topLeft.applying(transform))
ocrCandidates.append(.init(text: topCandidate.string, boundingPoints: boundingPoints))
}
if ocrCandidates.isEmpty {
ocrRequestDelegate?.ocrCompleted(result: .failure(OCRError.noTextFound))
} else {
let sortedOCRCandidates = ocrCandidates.sortCandidates()
ocrRequestDelegate?.ocrCompleted(result: .success(sortedOCRCandidates))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment