Name error: Image to text error in python
Name error: Image to text error in python
我正在开发使用以下代码将图像转换为文本的代码。我在执行代码时看到以下错误。我真的不明白是什么导致了这个问题。谁能帮我找出问题所在。
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)
错误如下:
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
您应该传递 img
对象而不是路径
text = pytesseract.image_to_string(img)
代码应该是这样的:
from PIL import Image
import pytesseract
from pytesseract import Output
img = Image.open('Sample.png')
pytesseract.pytesseract.tesseract_cmd = 'C:\AppData\Local\Tesseract-OCR\tesseract.exe'
print(pytesseract.image_to_string(img))
我正在开发使用以下代码将图像转换为文本的代码。我在执行代码时看到以下错误。我真的不明白是什么导致了这个问题。谁能帮我找出问题所在。
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)
错误如下:
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
您应该传递 img
对象而不是路径
text = pytesseract.image_to_string(img)
代码应该是这样的:
from PIL import Image
import pytesseract
from pytesseract import Output
img = Image.open('Sample.png')
pytesseract.pytesseract.tesseract_cmd = 'C:\AppData\Local\Tesseract-OCR\tesseract.exe'
print(pytesseract.image_to_string(img))