gpt4 book ai didi

ios - Firebase MLKit 文本识别错误

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:05 26 4
gpt4 key购买 nike

我正在尝试使用 Firebase MLKit 对我的图像进行 OCR,但失败并返回错误

Text detection failed with error: Failed to run text detector because self is 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 的强引用,否则检测器会在调用完成 block 之前被释放。

稍微更改一下代码:

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
}
}

你也可以解开它以确保它在你赋值后不为 nil:

guard let textDetector = textDetector else { 
print("Error: textDetector is nil.")
return
}

希望对您有所帮助!

关于ios - Firebase MLKit 文本识别错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com