Ошибка при импорте изображения PIL и импорте pytesser

Я новичок в Python. Я пытаюсь создать программу распознавания текста Python и следую онлайн-руководству по ней. Вот рекомендуемый код, который я использую:

from PIL import Image
from pytesser import *

image_file = 'menu.tif'
im = Image.open(image_file)
text = image_to_string(im)
text = image_file_to_string(image_file)
text = image_file_to_string(image_file, graceful_errors=True)
print "=====output=======\n"
print text

Ссылка на руководство находится здесь. Однако я получаю эту ошибку при запуске этого кода.

    from pytesser import *
ImportError: No module named 'pytesser'

Я выполнил инструкции по установке OCR здесь и библиотеки PyTesser здесь, код (точка) google (точка) com / archive / p / pytesser / downloads (извините, потому что ‹10 rep я не могу разместить более 2 ссылок).

Это (см. Gyazo ниже) - скриншот моих установочных файлов, где pytesser_v0.0.1 - моя папка pytesser, tesseract-master - найдена на GitHub (вероятно, не имеет отношения), а tessinstall - это папка, в которой Я установил tesseract и, наконец, pyimgr.py - это мой файл, который я пытаюсь запустить.

gyazo (точка) com / 333f8a3333e87895558f26875a8a8487

Я также ранее получал сообщение об ошибке при импорте изображения PIL. Мне не следует использовать PIL, есть ли другой способ импортировать изображение без PIL? может подушка?

Моя версия Python - 3.5.2, и я использую Windows 10.


person prime2017    schedule 20.08.2017    source источник


Ответы (2)


Моя первая догадка заключается в том, что ваша библиотека установлена ​​в месте, о котором Python не знает.

import sys
print sys.path

Если вы выполните эти строки в Python, он покажет вам, где Python будет искать яйца. Есть ли там pytesser lib?

Кроме того: в качестве примечания: pip3 search tesseract покажет вам некоторые другие пакеты tesseract Python. Таким образом, вы можете использовать диспетчер пакетов Python.

person Pullie    schedule 20.08.2017

Измените код на этот:

"""OCR in Python using the Tesseract engine from Google
http://code.google.com/p/pytesser/
by Michael J.T. O'Kelly
V 0.0.1, 3/10/07"""

import PIL.Image
import subprocess

import util
import errors

tesseract_exe_name = 'tesseract' # Name of executable to be called at command line
scratch_image_name = "temp.bmp" # This file must be .bmp or other Tesseract-compatible format
scratch_text_name_root = "temp" # Leave out the .txt extension
cleanup_scratch_flag = True  # Temporary files cleaned up after OCR operation

def call_tesseract(input_filename, output_filename):
    """Calls external tesseract.exe on input file (restrictions on types),
    outputting output_filename+'txt'"""
    args = [tesseract_exe_name, input_filename, output_filename]
    proc = subprocess.Popen(args)
    retcode = proc.wait()
    if retcode!=0:
        errors.check_for_errors()

def image_to_string(im, cleanup = cleanup_scratch_flag):
    """Converts im to file, applies tesseract, and fetches resulting text.
    If cleanup=True, delete scratch files after operation."""
    try:
        util.image_to_scratch(im, scratch_image_name)
        call_tesseract(scratch_image_name, scratch_text_name_root)
        text = util.retrieve_text(scratch_text_name_root)
    finally:
        if cleanup:
            util.perform_cleanup(scratch_image_name, scratch_text_name_root)
    return text

def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True):
    """Applies tesseract to filename; or, if image is incompatible and graceful_errors=True,
    converts to compatible format and then applies tesseract.  Fetches resulting text.
    If cleanup=True, delete scratch files after operation."""
    try:
        try:
            call_tesseract(filename, scratch_text_name_root)
            text = util.retrieve_text(scratch_text_name_root)
        except errors.Tesser_General_Exception:
            if graceful_errors:
                im = PIL.Image.open(filename)
                text = image_to_string(im, cleanup)
            else:
                raise
    finally:
        if cleanup:
            util.perform_cleanup(scratch_image_name, scratch_text_name_root)
    return text


if __name__=='__main__':
    im = PIL.Image.open('phototest.tif')
    text = image_to_string(im)
    print text
    try:
        text = image_file_to_string('fnord.tif', graceful_errors=False)
    except errors.Tesser_General_Exception, value:
        print "fnord.tif is incompatible filetype.  Try graceful_errors=True"
        print value
    text = image_file_to_string('fnord.tif', graceful_errors=True)
    print "fnord.tif contents:", text
    text = image_file_to_string('fonts_test.png', graceful_errors=True)
    print text
person Mahyar    schedule 18.03.2018