Nameerror: name 'pytesseract' is not defined

Asked

Viewed 327 times

0

I am using the Pytesseract and Opencv libraries to print a text from an image, but when trying to run the script it gives the following error:

img_text = pytesseract.image_to_string(img) Attributeerror: partially initialized module 'pytesseract' has no attribute 'image_to_string' (Most likely due to a circular import)

I have uninstalled and reinstalled pyteressact using pip3 a few times, but the error persists. I consulted some forums/tutorials and the documentation itself talks to use "image_to_string", one detail is that even though the imported pytesseract in the code, it does not provide any method. I’ll leave the code below in case there is some syntax error.

import cv2
import pytesseract

while True:
  img = cv2.imread('ph2_mask_copy.png')
  cv2.imshow('Image', img)
  img_text = pytesseract.image_to_string(img)
  print(img_text)

  key = cv2.waitKey(1)
  if key == 27:
    break

cv2.destroyAllWindows()

Stacktrace:

Traceback (Most recent call last): File "pytesseract.py", line 2, in import pytesseract File "/home/Alan/Projects/Digitsdetection/pytesseract.py", line 7, in img_text = pytesseract.image_to_string(img) Attributeerror: partially initialized module 'pytesseract' has no attribute 'image_to_string' (Most likely due to a circular import)

  • puts the full stacktrace to analyze

  • @Lucasmiranda ready

  • 6

    File "pytesseract.py", line 2. You named your file as pytesseract.py. When you do import pytesseract you are importing the file itself. Avoid doing this in Python.

  • @Woss changed the file name and worked, thank you very much!

  • 3

1 answer

0

According to the documentation in pypi.org:

# Simple image to string
print(pytesseract.image_to_string(Image.open('test.png')))

Try adding "Image.open" as below:

import cv2
import pytesseract

while True:
  img = cv2.imread('ph2_mask_copy.png')
  cv2.imshow('Image', img)
  img_text = pytesseract.image_to_string(Image.open(img))
  print(img_text)

  key = cv2.waitKey(1)
  if key == 27:
    break

cv2.destroyAllWindows()

In case of use with Opencv, it is necessary to convert the image to RGB format:

import cv2

img_cv = cv2.imread(r'/<path_to_image>/digits.png')

# By default OpenCV stores images in BGR format and since pytesseract assumes 
RGB format,
# we need to convert from BGR to RGB format/mode:
img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
print(pytesseract.image_to_string(img_rgb))
# OR
img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 
0)
print(pytesseract.image_to_string(img_rgb))

See the documentation in pypi.org

Browser other questions tagged

You are not signed in. Login or sign up in order to post.