Search code examples
iosswiftuiimagetesseract

How to process a taken image then view the results to "text View" using Swift?


I am trying to build a simple app with a single button. Click on the button to take a picture, then using "TesseractOCR" I am converting the written text in the image to a string text and view it in my "Text View".

I got everything done, the camera and "TesseractOCR", the only problem I am facing is the following:

 tesseract.image = UIImage(named: selectedImage)

Gives me this error:

Cannot convert value of type 'UIImage' to expected argument type 'String'.

Note: selectedImage suppose to be the name of the image that Tesseract takes to convert the image into text.

Here is my code:

import UIKit
import TesseractOCR

class secondViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, G8TesseractDelegate  {

    @IBOutlet weak var viewText: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func takePhoto(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerController.SourceType.camera
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }


    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard let selectedImage = info[.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        // Set photoImageView to display the selected image.
        if let tesseract = G8Tesseract(language: "eng") {
            tesseract.delegate = self
            tesseract.image = UIImage(named: selectedImage)
            tesseract.recognize()

            textView.text = tesseract.recognizedText

        }

        // Dismiss the picker.
        dismiss(animated: true, completion: nil)
    }

}

Solution

  • Replace

    tesseract.image = UIImage(named: selectedImage)
    

    with

    tesseract.image = selectedImage
    

    the UIImage(named:<#string#>) takes a string value repressing the name of the image in bundle , but here you don't need it , instead supply the image directly