我正在使用iOS 11的Vision框架来检测图像上的文本。

文本已被成功检测到,但是我们如何获取检测到的文本?

最佳答案



VNRecognizeTextRequest从iOS 13.0和macOS 10.15 开始工作。

这是一个代码片段,向您展示如何执行此操作:

let requestHandler = VNImageRequestHandler(url: imageURL, options: [:])

let request = VNRecognizeTextRequest { (request, error) in

    guard let observations = request.results as? [VNRecognizedTextObservation]
    else { return }

    for observation in observations {

        let topCandidate: [VNRecognizedText] = observation.topCandidates(1)

        if let recognizedText: VNRecognizedText = topCandidate.first {
            label.text = recognizedText.string
        }
    }
}

然后,您必须为recognitionLevel实例属性分配一个值:
// non-realtime asynchronous but accurate text recognition
request.recognitionLevel = VNRequestTextRecognitionLevel.accurate

// nearly realtime but not-accurate text recognition
request.recognitionLevel = VNRequestTextRecognitionLevel.fast

try? requestHandler.perform([request])

10-08 05:28