Search code examples
pythonpandasspyderpython-tesseract

Name error: Image to text error in python


I am working on developing code to convert image to text using the below code. I see the below error while executing the code. I dont really understand what is causing the issue. Can any one help me to identify the issue.


from PIL import Image
import PIL.Image

from pytesseract import image_to_string
import pytesseract

img = Image.open('C:\\Users\\Documents\\convert_image_to_text\\Sample.png') 
pytesseract.pytesseract.tesseract_cmd = 'C:\AppData\Local\Tesseract-OCR\tesseract.exe'
text = pytesseract.image_to_string('C:\\Users\\Documents\\convert_image_to_text\\Sample.png')
print(text)

Below is the error:


  File "C:/Users/Documents/convert_image_to_text/program_to_convert_image_to_text.py", line 21, in <module>
    text=image_to_string(img)

NameError: name 'img' is not defined


Solution

  • You should be passing the img object and not the path

    text = pytesseract.image_to_string(img)