
Код: Выделить всё
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
print(pytesseract.image_to_string(Image.open('/tmp/target.gif')))
Код: Выделить всё
/usr/lib/python3/dist-packages/PIL/Image.py:925: UserWarning: Couldn't allocate palette entry for transparency
"for transparency")
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.5/dist-packages/pytesseract/pytesseract.py", line 309, in image_to_string
}[output_type]()
File "/usr/local/lib/python3.5/dist-packages/pytesseract/pytesseract.py", line 308, in
Output.STRING: lambda: run_and_get_output(*args),
File "/usr/local/lib/python3.5/dist-packages/pytesseract/pytesseract.py", line 208, in run_and_get_output
temp_name, input_filename = save_image(image)
File "/usr/local/lib/python3.5/dist-packages/pytesseract/pytesseract.py", line 136, in save_image
image.save(input_file_name, format=img_extension, **image.info)
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1728, in save
save_handler(self, fp, filename)
File "/usr/lib/python3/dist-packages/PIL/GifImagePlugin.py", line 407, in _save
_get_local_header(fp, im, (0, 0), flags)
File "/usr/lib/python3/dist-packages/PIL/GifImagePlugin.py", line 441, in _get_local_header
transparency = int(transparency)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
Код: Выделить всё
convert "/tmp/target.gif" "/tmp/target.jpg"

Затем снова выполните приведенный выше код Python.
Код: Выделить всё
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
print(pytesseract.image_to_string(Image.open('/tmp/target.jpg')))

Для Код Trenton_M:
Код: Выделить всё
>>> img1 = remove_noise_and_smooth(r'/tmp/target.jpg')
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in remove_noise_and_smooth
AttributeError: 'NoneType' object has no attribute 'astype'
Thalish Sajeed
[img]https: //i.stack.imgur.com/LSY3r.png[/img]
Опустить информацию об ошибке, вызванной print(pytesseract.image_to_string(Image.open(filename)) ).
Код: Выделить всё
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> import pytesseract
>>> import matplotlib.pyplot as plt
>>> import cv2
>>> import numpy as np
>>>
>>>
>>> def display_image(filename, length_box=60, width_box=30):
... if type(filename) == np.ndarray:
... image = filename
... else:
... image = cv2.imread(filename)
... plt.figure(figsize=(length_box, width_box))
... plt.imshow(image, cmap="gray")
...
>>>
>>> filename = r"/tmp/target.jpg"
>>> display_image(filename)
Traceback (most recent call last):
File "", line 1, in
File "", line 7, in display_image
File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 2699, in imshow
None else {}), **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py", line 1810, in inner
return func(ax, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_axes.py", line 5494, in imshow
im.set_data(X)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 634, in set_data
raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float
>>>
Вот мой проверенный образец файла.< /p>

извлеченная строка.

< /p>
@Trenton_M, исправьте небольшую опечатку и потерю в своем коде и удалите строку plt.show() по вашему предложению.
Код: Выделить всё
>>> import cv2,pytesseract
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>>
>>> def image_smoothening(img):
... ret1, th1 = cv2.threshold(img, 88, 255, cv2.THRESH_BINARY)
... ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
... blur = cv2.GaussianBlur(th2, (5, 5), 0)
... ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
... return th3
...
>>>
>>> def remove_noise_and_smooth(file_name):
... img = cv2.imread(file_name, 0)
... filtered = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 41)
... kernel = np.ones((1, 1), np.uint8)
... opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel)
... closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
... img = image_smoothening(img)
... or_image = cv2.bitwise_or(img, closing)
... return or_image
...
>>>
>>> cv2_thresh_list = [cv2.THRESH_BINARY, cv2.THRESH_TRUNC, cv2.THRESH_TOZERO]
>>> fn = r'/tmp/target.jpg'
>>> img1 = remove_noise_and_smooth(fn)
>>> img2 = cv2.imread(fn, 0)
>>> for i, img in enumerate([img1, img2]):
... img_type = {0: 'Preprocessed Images\n',
... 1: '\nUnprocessed Images\n'}
... print(img_type[i])
... for item in cv2_thresh_list:
... print('Thresh: {}'.format(str(item)))
... _, thresh = cv2.threshold(img, 127, 255, item)
... plt.imshow(thresh, 'gray')
... f_name = '{0}.jpg'.format(str(item))
... plt.savefig(f_name)
... print('OCR Result: {}\n'.format(pytesseract.image_to_string(f_name)))
Предварительно обработанные изображения
В моей консоли вся выводимая информация выглядит следующим образом: :
Код: Выделить всё
Thresh: 0
OCR Result: 10
15
20
Edfifi
10
2 o 30 40 so
so
Thresh: 2
OCR Result: 10
15
20
Edfifi
10
2 o 30 40 so
so
Thresh: 3
OCR Result: 10
15
20
Edfifi
10
2 o 30 40 so
so
Unprocessed Images
Thresh: 0
OCR Result: 10
15
20
Thresh: 2
OCR Result: 10
15
2o
2o
30 40 50
Thresh: 3
OCR Result: 10
15
20
Подробнее здесь: https://stackoverflow.com/questions/571 ... rlay-lines