Last active
August 4, 2023 13:22
-
-
Save craigmarvelley/a2135c713cd38e17e9f70ffaa7722697 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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