Pytesseract: "Ошибка TesseractNotFound: tesseract не установлен или он не на вашем пути", как я могу это исправить? - программирование
Подтвердить что ты не робот

Pytesseract: "Ошибка TesseractNotFound: tesseract не установлен или он не на вашем пути", как я могу это исправить?

Я пытаюсь запустить простой и очень простой код в python.

from PIL import Image
import pytesseract

im = Image.open("sample1.jpg")

text = pytesseract.image_to_string(im, lang = 'eng')

print(text)

Это то, на что похоже, я действительно установил tesseract для окон через установщик. Я очень новичок в Python, и я не уверен, как это сделать?

Любое руководство здесь было бы очень полезно. Я попытался перезапустить приложение Spyder, но безрезультатно.

4b9b3361

Ответ 1

Я вижу шаги разбросаны по разным ответам. Основываясь на моем недавнем опыте с этой ошибкой pytesseract в Windows, я написал несколько последовательных шагов, чтобы упростить ее устранение:

1. Установите tesseract с помощью установщика Windows, доступного по адресу: https://github.com/UB-Mannheim/tesseract/wiki

2. Обратите внимание на путь tesseract из установки. Путь установки по умолчанию во время этого редактирования был: C:\Users\USER\AppData\Local\Tesseract-OCR. Это может измениться, поэтому, пожалуйста, проверьте путь установки.

3. pip install pytesseract

4. установите путь к тессеракту в скрипте перед вызовом image_to_string:

pytesseract.pytesseract.tesseract_cmd = r'C:\Users\USER\AppData\Local\Tesseract-OCR\tesseract.exe'

Ответ 2

Сначала вы должны установить бинарный файл:

В Linux

sudo apt-get update
sudo apt-get install tesseract-ocr
sudo apt-get install libtesseract-dev

на Mac

brew install tesseract

В Windows

скачать бинарный файл из https://github.com/UB-Mannheim/tesseract/wiki. затем добавьте pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe' в ваш скрипт.

Затем вы должны установить пакет Python, используя pip:

pip install tesseract
pip install tesseract-ocr

ссылки: https://pypi.org/project/pytesseract/ (раздел УСТАНОВКА) иhttps://github.com/tesseract-ocr/tesseract/wiki#installation

Ответ 3

В окнах:

pip install tesseract

pip install tesseract-ocr

и проверьте файл, который хранится в вашей системе usr/appdata/local/programs/site-pakages/python/python36/lib/pytesseract/pytesseract.py и скомпилируйте файл

Ответ 4

С https://pypi.org/project/pytesseract/ :

pytesseract.pytesseract.tesseract_cmd = '<full_path_to_your_tesseract_executable>'
# Include the above line, if you don't have tesseract executable in your PATH
# Example tesseract_cmd: 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'

Ответ 5

Только для Windows


1 - на вашем компьютере должна быть установлена программа распознавания текста Tesseract.

get it from here. https://github.com/UB-Mannheim/tesseract/wiki

Загрузите подходящую версию.

2 - Сохраните путь tesseract в вашей системной среде. редактировать системные переменные.

3 - pes install pytesseract и pip install tesseract

4 - Добавьте эту строку в ваш скрипт на Python

pytesseract.pytesseract.tesseract_cmd = 'C:\\OCR\\Tesseract-OCR\\tesseract.exe' ^ Ваш путь может быть другим.

5 - прогнать код.

Ответ 6

вы можете установить этот пакет... https://github.com/UB-Mannheim/tesseract/wiki после этого вы должны пойти по этому пути C:\Program Files (x86)\Tesseract-OCR\tesseract.exe затем запустить файл tesseract, Я думаю, это поможет вам...

Ответ 7

Вам понадобится установить tesseract.

https://github.com/tesseract-ocr/tesseract/wiki

Ознакомьтесь с приведенной выше документацией по установке.

Ответ 8

На маке (у меня работает)

brew install tesseract

Ответ 9

Используйте следующую команду для установки tesseract

pip install tesseract

Ответ 10

Шаг 1:

Установите tesseract в вашей системе в соответствии с ОС. Последние установщики можно найти по адресу https://github.com/UB-Mannheim/tesseract/wiki.

Шаг 2: Установите следующие библиотеки зависимостей, используя: pip install pytesseract pip install opencv-python pip install numpy

Шаг 3: Пример кода

import cv2
import numpy as np
import pytesseract
from PIL import Image
from pytesseract import image_to_string

# Path of working folder on Disk Replace with your working folder
src_path = "C:\\Users\\<user>\\PycharmProjects\\ImageToText\\input\\"
# If you don't have tesseract executable in your PATH, include the 
following:
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract- 
OCR/tesseract'
TESSDATA_PREFIX = 'C:/Program Files (x86)/Tesseract-OCR'

def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)

    # Write image after removed noise
    cv2.imwrite(src_path + "removed_noise.png", img)

    #  Apply threshold to get image with only black and white
    #img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)

    # Write the image after apply opencv to do some ...
    cv2.imwrite(src_path + "thres.png", img)

    # Recognize text with tesseract for python
    result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))

    # Remove template file
    #os.remove(temp)

    return result


print('--- Start recognize text from image ---')
print(get_string(src_path + "image.png") )

print("------ Done -------")

Ответ 11

В Windows путь к команде должен быть перенаправлен для установки по умолчанию в Windows.

  1. В 32-битной системе добавьте в эту строку после команд импорта.
pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe' 
  1. В 64-битной системе добавьте эту строку вместо этого.
 pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files\Tesseract-OCR\tesseract.exe'

Ответ 12

# {Windows 10 instructions}
# before you use the script you need to install the dependence
# 1. download the tesseract from the official link:
#   https://github.com/UB-Mannheim/tesseract/wiki
# 2. install the tesseract
#   i chosed this path
#       *replace the user string in the below path with you name of user that you are using in your current machine
#       C:\Users\user\AppData\Local\Tesseract-OCR\
# 3. Install the  pillow for your python version
# * the best way for me is to install is this form(i'am using python3.7 version and in my CMD i run this version of python by     typing py -3.7):
# * if you are using another version of python first look how you start the python from you CMD
# * for some machine the run of python from the CMD is different
    # [examples]
    # =================================
    # PYTHON VERSION 3.7
    # python
    # python3.7
    # python -3.7
    # python 3.7
    # python3
    # python -3
    # python 3
    # py3.7
    # py -3.7
    # py 3.7
    # py3
    # py -3
    # py 3
    # PYTHON VERSION 3.6
    # python
    # python3.6
    # python -3.6
    # python 3.6
    # python3
    # python -3
    # python 3
    # py3.6
    # py -3.6
    # py 3.6
    # py3
    # py -3
    # py 3
    # PYTHON VERSION 2.7
    # python
    # python2.7
    # python -2.7
    # python 2.7
    # python2
    # python -2
    # python 2
    # py2.7
    # py -2.7
    # py 2.7
    # py2
    # py -2
    # py 2
    # ================================
# we are using pip to install the dependences
# because for me i start the python version 3.7 with the following line 
    # py -3.7
# open the CMD in windows machine and type the following line:
    # py -3.7 -m pip install pillow
# 4. Install the  pytesseract and tesseract for your python version
# * the best way for me is to install is this form(i'am using python3.7 version and in my CMD i run this version of python by     typing py -3.7):
# we are using pip to install the dependences
# open the CMD in windows machine and type the following lines:
    # py -3.7 -m pip install pytesseract
    # py -3.7 -m pip install tesseract


#!/usr/bin/python
from PIL import Image
import pytesseract
import os
import getpass

def extract_text_from_image(image_file_name_arg):

    # IMPORTANT
    # if you have followed my instructions to install this dependence in above text explanatin
    # for my machine is
    # if you don't put the right path for tesseract.exe the script will not work
    username = getpass.getuser()
    # here above line get the username for your machine automatically
    tesseract_exe_path_installation="C:\\Users\\"+username+"\\AppData\\Local\\Tesseract-OCR\\tesseract.exe"
    pytesseract.pytesseract.tesseract_cmd=tesseract_exe_path_installation

# specify the direction of your image files manually or use line bellow if the images are in the script directory in     folder  images
    # image_dir="D:\\GIT\\ai_example\\extract_text_from_image\\images"
    image_dir=os.getcwd()+"\\images"
    dir_seperator="\\"
    image_file_name=image_file_name_arg
    # if your image are in different format change the extension(ex. ".png")
    image_ext=".jpg"
    image_path_dir=image_dir+dir_seperator+image_file_name+image_ext

    print("=============================================================================")
    print("image used is in the following path dir:")
    print("\t"+image_path_dir)
    print("=============================================================================")

    img=Image.open(image_path_dir)
    text=pytesseract.image_to_string(img, lang="eng")
    print(text)

# change the name "image_1" whith the name without extension for your image name
# image_file_name_arg="image_1"
image_file_name_arg="image_2"
# image_file_name_arg="image_3"
# image_file_name_arg="image_4"
# image_file_name_arg="image_5"
extract_text_from_image(image_file_name_arg)

# ==================================
# CREATED BY: SHERIFI
# e-mail: [email protected]
# git-link for script: https://github.com/sherifi/ai_example.git
# ==================================

Ответ 13

For Ubuntu 18.04

Если вы получаете сообщение об ошибке типа

 tesseract is not installed or it not in your path

 and 

 OSError: [Errno 12] Cannot allocate memory

Это может быть связано с проблемой выделения памяти подкачки

Вы можете проверить этот ответ, выделив больше памяти подкачки. Надеюсь, это поможет :)

https://askubuntu.com/info/920595/fallocate-fallocate-failed-text-file-busy-in-ubuntu-17-04?answertab=active#tab-top