前言
想研究一下 apple 自带的 OCR 接口,查了点资料后,感觉效果还挺不错的~
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import Vision
func processImage() { guard let cgImage = UIImage(named: "snapshot")?.cgImage else { return }
let requestHandler = VNImageRequestHandler(cgImage: cgImage) let request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler) request.recognitionLevel = .accurate // 采用精确路径 request.recognitionLanguages = ["zh-Hans", "en-US"] // 设置识别的语言
do { try requestHandler.perform([request]) } catch { print("Unable to perform the requests: \(error).") } }
func recognizeTextHandler(request: VNRequest, error: Error?) { guard let observations = request.results as? [VNRecognizedTextObservation] else { return } let recognizedStrings = observations.compactMap { observation in return observation.topCandidates(1).first?.string } print(recognizedStrings.joined(separator: " ")) }
|
识别二维码
如果想要识别二维码的话,可以这么做
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let barcodeRequest = VNDetectBarcodesRequest(completionHandler: { request, error in guard let results = request.results else { return } for result in results { if let barcode = result as? VNBarcodeObservation { /// 二维码内容 print(barcode.payloadStringValue) print("Symbology: \(barcode.symbology.rawValue)") if let desc = barcode.barcodeDescriptor as? CIQRCodeDescriptor { let content = String(data: desc.errorCorrectedPayload, encoding: .utf8) print("Payload: \(String(describing: content))") print("Error-Correction-Level: \(desc.errorCorrectionLevel)") print("Symbol-Version: \(desc.symbolVersion)") } } } })
|
参考
用苹果官方 API 实现 iOS 备忘录的扫描文稿功能
Recognizing Text in Images
关于系统的 Live Text
iOS 15 UITextField长按菜单支持live text 扫描插入文字功能