I'm currently building a small CLI tool in Swift 5.4 and wanted to use the Vision Framework to extract all the text in an Image. The Article I'm following to accomplish this task is provided by Apple and can be found here. As you can see my code is the same as the example provided by Apple and is currently not working.
This is the compile error:
error: argument passed to call that takes no arguments
let request = VNRecognizeTextRequest(completion: recognizeTextRequestHandler)
This is code with the VNRecognizeTextRequest
class and there recognizeTextRequestHandler
function is passed to the constructor to process the result.
@available(macOS 10.13, *)
public func run() throws {
// Get the image from argument and create a UIImage
let file = try Files.File.init(path: arguments[1]).read()
guard let image = UIImage(data: file)?.cgImage else { return }
// request
let imageRequestHandler = VNImageRequestHandler(cgImage: image)
// pass handler to process the result
let request = VNRecognizeTextRequest(completion: recognizeTextRequestHandler)
do {
// Perform the text-recognition request.
try imageRequestHandler.perform([request])
} catch {
print("Unable to perform the requests: \(error).")
}
}
The function which is passed into VNRecognizeTextRequest
@available(macOS 10.13, *)
func recognizeTextRequestHandler(request: VNRequest, error: Error?){
if #available(macOS 10.15, *) {
guard let observations =
request.results as? [VNRecognizedTextObservation] else {
return
}
let recognizedStrings = observations.compactMap { observation in
// Return the string of the top VNRecognizedText instance.
return observation.topCandidates(1).first?.string
}
// Process the recognized strings.
print(recognizedStrings)
} else {
exit(EXIT_FAILURE)
}
Thank you for your time! If something is not clear please comment.
The article is outdated - it should be completionHandler
, not completion
. Replace:
let request = VNRecognizeTextRequest(completion: recognizeTextRequestHandler)
... with:
let request = VNRecognizeTextRequest(completionHandler: recognizeTextRequestHandler)