0

I am using pytesseract to read image as text in python. Following is my code:

from PIL import Image
from pytesseract import image_to_string
import os.path

if (os.path.exists('image.png')):
    filename = 'image.png'
    image = Image.open(filename)
    image.show()
    s = image_to_string(Image.open(filename))
else:
    print('Does not exist')

The code gets the file image.png, opens it and show the image to me which means the file exists in that directory. But when it goes to next line s = image_to_string(Image.open(filename)) it gives the following error.

Traceback (most recent call last):
  File "C:/Users/hp/Desktop/GII/Genetic_Algorithm.py", line 8, in <module>
    s = image_to_string(Image.open(filename))
  File "C:\Users\hp\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\pytesseract\pytesseract.py", line 161, in image_to_string
    config=config)
  File "C:\Users\hp\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\pytesseract\pytesseract.py", line 94, in run_tesseract
    stderr=subprocess.PIPE)
  File "C:\Users\hp\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
  File "C:\Users\hp\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\subprocess.py", line 1220, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

I tried hard but do not know how to handle this.

muazfaiz
  • 4,611
  • 14
  • 50
  • 88

1 Answers1

0

maybe try :

f2 = os.path.abspath(filename)

s = image_to_string(Image.open(f2))

PIL is apparently using some subprocess, that may not have the same "default directory" than the main process

stonebig
  • 1,193
  • 1
  • 9
  • 13
  • I am getting the same error again. I thinl PIL is not creating problems because I can open the image using Image.open(filename) but if you see the above error it is occuring when I am using `pytesseract`. – muazfaiz Jul 24 '16 at 19:20
  • other idea; you open twice the file, so the second time, the file is unavailable. so, maybe try "s = image_to_string(image)" – stonebig Jul 24 '16 at 19:46
  • I didn't exactly get what you are trying to say. I think even If I open the file twice it will not change the path problem. Can you please write your intuition. Thanks – muazfaiz Jul 24 '16 at 19:53
  • Maybe the "Image.open()" is opening the file in read/write mode, so opening two times the same file, as in your code, is the problem. – stonebig Jul 25 '16 at 17:23