Vision 是用于各种识别的框架,比如人脸识别、文字识别等。本篇文章只介绍图片文字识别的部分,只是因为在最近的项目中有用到过,其他的识别方式以后可能会更新。
先上代码
extension UIImage {
/// 提取图片中的文字
func textExtraction() -> String {
guard let cgImage = self.cgImage else {
return ""
}
var result = ""
let request = VNRecognizeTextRequest { request, _ in
guard let observations = request.results as? [VNRecognizedTextObservation] else {
return
}
let recognizedStrings = observations.compactMap { observation in
observation.topCandidates(1).first?.string
}
result = recognizedStrings.joined(separator: "\n")
}
request.recognitionLevel = .accurate // 采用精确路径
request.recognitionLanguages = ["zh-Hans", "en-US"] // 设置识别语言
let requestHandler = VNImageRequestHandler(cgImage: cgImage)
do {
try? requestHandler.perform([request])
} catch {
fatalError("error = \(error.localizedDescription)")
}
return result
}
}
以上就是图片文字识别的基本代码了,但是这个方法有缺陷,