1.添加Vision Kit依赖
在项目设置中点击"General"选项卡,然后在"Frameworks, Libraries, and Embedded Content"(框架、库和嵌入内容)部分,点击"+"按钮。搜索并选择"Vision.framework"。
2.代码实现
import Visionfunc recognizeText (image: CGImage){ let request = VNRecognizeTextRequest { (request , error) in if let results = request.results as ?[VNRecognizedTextObservation]{//处理识别结果 let recognizedStrings = results.compactMap { observation in return observation.topCandidates(1).first?.string } print ("识别结果:\(recognizedStrings)") self.result.text = recognizedStrings.joined (separator:"\n")}}//设置最小置信度来过滤结果 request.minimumTextHeight =1 //精确识别,fast则为快速识别request.recognitionLevel =.accurate//创建图片请求处理器 let requestHandler = VNImageRequestHandler(cgImage: image , options :[:])//执行请求 do { try requestHandler.perform ([request])} catch {print ("文字识别失败:\(error)")}
}
3.识别结果
速度很快,但亲测识别准确率有限。部分识别文字错误。
提高中文识别成功率,可以设置
request.recognitionLanguages = ["zh-Hans"]