Slice Horrest Slice Horrest - 1 year ago 57
Swift Question

Pulling text from an image and input into a textfield with Tesseract OCR

I'm using Tesseract OCR and I want it to take a picture of an image and input selective words into textfields, I'm able to take the entire image completely and put it in a textfield, but I don't know how to take separate words and put them in separate TextFields.

Can someone either point me in the right direction or name the functions and statements I would need to make it work?

Answer Source


I've figured it out, using regex you can pull specific text from an image. For example let's say you want to pull a Zip Code from the address and you ran it through the Tesseract OCR. It will find the text in the image and out put it into a string. If you don't know how to do that just ask and I'll post a separate question and answer for that one. You get the string and now you want to pull the Zip Code.

Let's say the Address is 0000 Stainly St, Water, IA, 50703 -- this is a fake address

 @IBOutlet weak var zipcode: UITextField!

  override func viewDidLoad() {

        zipcode.text = getZip()


  //Gets the text from image
var recognizedText : String!
//Set up the extraction function for the text extractoin from the recognizedText
func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
            options: [], range: NSMakeRange(0, nsString.length))
        return { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []

//Function to get zip from the text
  func getZip() -> String {
    //below is the regex pattern to get zipcodes 
    let zipAddress = matchesForRegexInText("\\d{5}(?:[-\\s]\\d{4})?", text: recognizedText)

    if zipAddress.isEmpty {
        return "Could Not Identify, Tap to Enter Zipcode"
    } else {
        return zipAddress[0]

If anyone has any questions feel free to ask.