Firebase MLKit 文字识别错误

4

我正在尝试使用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)
    }
}

请在给出差评之前帮助我或告知我哪里出了问题。 - NITESH
我没有看到vision被声明的地方,但我希望你没有忘记声明它:lazy var vision = Vision.vision() - Rosário Pereira Fernandes
你好,你解决了这个问题吗?我也遇到了同样的错误。 - Jason
2个回答

9

看起来你需要保持对 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
    }
}

你可以在赋值后对它进行解包,以确保它不是 nil:

您可以使用解包(unwrap)来确保它在赋值后不是 nil:

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

我希望你能够受益于以下内容!

1

VisionTextDetector不再受支持,因此您需要使用VisionTextRecognizer。 这是一个示例代码,希望对您有所帮助。

   //MARK: Firebase var
 lazy var vision = Vision.vision()
   // replace VisionTextDetector with VisionTextRecognizer
     var textDetector:  VisionTextRecognizer? 

    override func viewDidLoad() {
        super.viewDidLoad()

        textDetector = vision.onDeviceTextRecognizer()
    }

// also instead of using detect use process now

     textDetector!.process(image) { result, error in

                guard error == nil, let result = result else {
                   //error stuff

                    return

                }
                let text = result.text
                self.textV.text = self.textV.text + " " + text
            }
        }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接