ios - Firebase MLKit 文本识别错误
问题描述
我正在尝试使用 Firebase MLKit 对我的图像进行 OCR,但它失败并返回错误
文本检测失败并出现错误:无法运行文本检测器,因为 self 为 nil。
/// 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
,否则检测器会在调用完成块之前被释放。
稍微改变你的代码:
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
}
}
您还可以打开它以确保它在分配后不为零:
guard let textDetector = textDetector else {
print("Error: textDetector is nil.")
return
}
我希望这会有所帮助!
推荐阅读
- java - 来自 Java 的 Discord Webhook 消息中的表情符号和特殊字符不起作用
- substrate - 尝试访问远程托管前端substrate-fronend-template时出现错误1006异常关闭
- swift - swift mapView 和一个按钮。我无法从 mapKit 获得任何触摸事件
- jquery - 自动列隐藏
- powershell - 简单的PowerShell,括号内的变量不起作用
- sql - 在 postgres 中实现多个连续聚合的最佳方法
- c++ - 在插入期间提升 r-tree 打包算法
- python - EasyOCR 脚本运行错误 - 没有名为“torch.backends”的模块
- css - 将元素粘贴到 woocommerce 产品页面的右侧
- php - 在构造函数中使用 DI 类别名?