本文介绍了Firebase MLKit文本识别错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Firebase MLKit OCR我的图像,但是它失败并返回错误
I'm trying to OCR my image using Firebase MLKit but it fails and return with error
/// Detects texts on the specified image and draws a frame for them.
func detectTexts() {
let image = #imageLiteral(resourceName: "testocr")
// Create a text detector.
let textDetector = vision.textDetector() // Check console for errors.
// Initialize a VisionImage with a UIImage.
let visionImage = VisionImage(image: image)
textDetector.detect(in: visionImage) { (features, error) in
guard error == nil, let features = features, !features.isEmpty else {
let errorString = error?.localizedDescription ?? "No results returned."
print("Text detection failed with error: \(errorString)")
return
}
// Recognized and extracted text
print("Detected text has: \(features.count) blocks")
let resultText = features.map { feature in
return "Text: \(feature.text)"
}.joined(separator: "\n")
print(resultText)
}
}
推荐答案
您似乎需要保持对textDetector
的强引用,否则检测器会在可以调用完成块之前被释放.
It looks like you need to keep a strong reference to textDetector
, otherwise the detector gets released before the completion block can be called.
稍微更改代码:
var textDetector: VisionTextDetector? // NEW
/// Detects texts on the specified image and draws a frame for them.
func detectTexts() {
// ... truncated ...
textDetector = vision.textDetector() // NEW
let visionImage = VisionImage(image: image)
textDetector?.detect(in: visionImage) { (features, error) in // NEW
// Callback implementation
}
}
您还可以将其解包,以确保分配后它不为零:
You can also unwrap it to make sure it's not nil after you assign it:
guard let textDetector = textDetector else {
print("Error: textDetector is nil.")
return
}
希望对您有帮助!
这篇关于Firebase MLKit文本识别错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!