Firebase MLKit文本识别错误

时间:2018-05-09 06:27:47

标签: ios swift firebase 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)
    }
}

2 个答案:

答案 0 :(得分: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
    }
}

您也可以打开它以确保在分配后不会为零:

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

我希望有所帮助!

答案 1 :(得分:0)

不再支持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
            }
        }