Firebase MLKit Text Recognition Error

℡╲_俬逩灬. 提交于 2019-12-05 01:06:56

问题


I'm trying to OCR my image using Firebase MLKit but it fails and return with error

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

回答1:


It looks like you need to keep a strong reference to textDetector, otherwise the detector gets released before the completion block can be called.

Changing your code a bit:

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
}

I hope that helps!




回答2:


VisionTextDetector is no more supported so you have to use VisionTextRecognizer. Here is an example code and I hope its helpful

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



来源:https://stackoverflow.com/questions/50246800/firebase-mlkit-text-recognition-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!