【问题标题】:Firebase MLKit Text Recognition ErrorFirebase MLKit 文本识别错误
【发布时间】:2018-05-09 06:27:47
【问题描述】:

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

【问题讨论】:

  • 在投反对票之前请帮助我或让我知道出了什么问题。
  • 我没有看到vision 是在哪里声明的,但我希望你不要忘记声明它:lazy var vision = Vision.vision()
  • 您好,您解决了吗?我得到了同样的错误

标签: ios swift firebase firebase-mlkit


【解决方案1】:

看来您需要保持对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:

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

希望对你有帮助!

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多