2

I am trying to use MLKit in my project, but I can't initialize TextRecognizer. I tried this:

textRecognizer = TextRecognizer.textRecognizer()

Which gives a warning:

'textRecognizer()' is deprecated: Please use textRecognizer(options:) instead

However, when I try to initialize it this way:

let options = CommonTextRecognizerOptions.init()
textRecognizer = TextRecognizer.textRecognizer(options: options)

I get this error:

'init()' is unavailable

How am I supposed to initialize it then?

Thank you for your help

aheze
  • 24,434
  • 8
  • 68
  • 125
Another Dude
  • 1,204
  • 4
  • 15
  • 33

2 Answers2

2

From the documentation for CommonTextRecognizerOptions:

-init
Unavailable. Use the initializers in subclasses.

So you'll need to use a subclass of CommonTextRecognizerOptions. Here's what I found:

/// Configurations for a text recognizer for Latin-based languages.
TextRecognizerOptions()

/// Configurations for a text recognizer for Chinese and Latin-based languages.
ChineseTextRecognizerOptions()

/// Configurations for a text recognizer for Devanagari and Latin-based languages.
DevanagariTextRecognizerOptions()

/// Configurations for a text recognizer for Japanese and Latin-based languages.
JapaneseTextRecognizerOptions()

/// Configurations for a text recognizer for Korean and Latin-based languages.
KoreanTextRecognizerOptions()

You'd use it like this:

let options = TextRecognizerOptions() /// same thing as `TextRecognizerOptions.init()`
textRecognizer = TextRecognizer.textRecognizer(options: options)
aheze
  • 24,434
  • 8
  • 68
  • 125
  • 1
    Yes, there are some code snippet here as examples: https://developers.google.com/ml-kit/vision/text-recognition/v2/ios#1_create_an_instance_of_textrecognizer – Julie Zhou Sep 08 '21 at 01:15
1

Here is how I did it:

func runTextRecognition(with image: UIImage) {
    let visionImage = VisionImage(image: image)
    //This is the initialisation
    let latinOptions = TextRecognizerOptions()
    let latinTextRecognizer = TextRecognizer.textRecognizer(options: latinOptions)
    
    latinTextRecognizer.process(visionImage) { features, error in
        self.processResult(from: features, error: error)
    }
}

func processResult(from text: Text?, error: Error?) {
    guard error == nil, let text = text else {
        let errorString = error?.localizedDescription
        print("Text recognizer failed with error: \(String(describing: errorString))")
        return
    }
    //Blocks.
    for block in text.blocks {
        //Lines.
        for line in block.lines {
            //This is your result
            print(block result: block.text, line result: line.text)
        }
    }
}

Hopefully it helps someone =)

Linus
  • 423
  • 5
  • 12