Swift Vision Framework - VNRecognizeTextRequest:传递给不带参数的调用的参数

问题描述

我目前正在 Swift 5.4 中构建一个小型 CLI 工具,并希望使用 Vision Framework 提取图像中的所有文本。我为完成此任务而关注的文章由 Apple 提供,可以在 here 中找到。如您所见,我的代码与 Apple 提供的示例相同,目前无法运行。

这是编译错误

error: argument passed to call that takes no arguments
        let request = VNRecognizeTextRequest(completion: recognizeTextRequestHandler)

这是带有 VNRecognizeTextRequest 类的代码,其中 recognizeTextRequestHandler 函数被传递给构造函数以处理结果。

@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).")
        }
    }

传入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)
    }

感谢您的时间!如果有什么不明白的请评论

解决方法

文章已过时 - 应该是 completionHandler,而不是 completion。替换:

let request = VNRecognizeTextRequest(completion: recognizeTextRequestHandler)

...与:

let request = VNRecognizeTextRequest(completionHandler: recognizeTextRequestHandler)
,

使用这个构造函数

let request = VNRecognizeTextRequest(completionHandler: recognizeTextRequestHandler)