NIT*_*ESH 4 ios firebase swift firebase-mlkit
我正在尝试使用Firebase MLKit OCR我的图像,但它失败并返回错误
文本检测失败并显示错误:无法运行文本检测器,因为self为零.
/// 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)
}
}
Run Code Online (Sandbox Code Playgroud)
看起来您需要保持强引用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
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以打开它以确保在分配之后它不是零:
guard let textDetector = textDetector else {
print("Error: textDetector is nil.")
return
}
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助!
| 归档时间: |
|
| 查看次数: |
2310 次 |
| 最近记录: |