How to restrict the recognized characters in tesserocr? - python

When using tesserocr how do I limit the set of characters that Tesseract will recognize to just the digits?
I know from this that if I were using c++ I could set a tessedit_char_whitelist in the config file, but I don't know the analogous approach in tesserocr within Python.
In general, the tesserocr documentation gives help that works if the reader already knows the Tesseract API for c++. As I am not fluent in c++, I am hoping to avoid having to read the c++ source code in order to use tesserocr.
If anyone can give me what I actually need to write in python or a general rule for going from config settings to Python code that would be great. Thanks in advance.

Tesserocr works as the C++ API, you can set a whitelist with the function SetVariable.
An example:
from tesserocr import PyTessBaseAPI
from string import digits
with PyTessBaseAPI() as api:
api.SetVariable('tessedit_char_whitelist', digits)
api.SetImageFile('image.png')
print api.GetUTF8Text() # it will print only digits
If you want another approach that is more straightforward and independent from the C++ API, try with the pytesseract module.
An example with pytesseract:
import pytesseract
from PIL import Image
from string import digits
image = Image.open('image.png')
print pytesseract.image_to_string(
image, config='-c tessedit_char_whitelist=' + digits)

Related

Pytesseract can not recognize even very simple textline

Binary image B2
Binary image Y2
I think these images are quite simple and clear. Still pytesseract does not work. I really wonder why.
Here is my code
from pytesseract import pytesseract as tesseract
import cv2 as cv
binary = cv.imread(filepath)
lang = 'eng'
config = 'tessedit_char_whitelist=RGB123'
print(tesseract.image_to_string(binary, lang=lang, config=config))
The output is just blank string.
To Dennlinger's point, I would definitely rotate it before sending it through PyTess. PyTess should rotate it automatically though. Should.
Alternatively, I see in your configuration that you have white listed "RGB123" which, correct me if I'm wrong, may mean that PyTess is mainly looking for those specific numbers and characters.
I'd try changing your configuration by omiting that configuration so that it can pick up the "Y" in there.

Can't create OCR using this path

I am trying to use pytesseract for OCR:
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd='C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
img=cv2.imread('numbers.png')
after running the code I get this message:
Unable to create process using 'C:\Users\Mostafa\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe C:/Users/Mostafa/PycharmProjects/pythonProject/main.py'
These are the installed packages:
The problem might be with 'Program Files' because since there is a space in the middle that makes the program unhappy. Inserting a double quotes should be enough to make the program understand it should ignore that space in the middle. I Once had a problem with that and adding double quotes worked like a charm.
"\Program Files"\

Using multiple languages in Pytesser

I have started to use Pytesser, which works great with both english and chinese, but is there a way to have both languages work at the same time? Would I have to make my own traineddata file? My code is:
import Image
from pytesser import *
print image_to_string(Image.open("chinese_and_english.jpg"), lang="eng")
#also want to have chinese be recognized
I'm not sure about Pytesser but using tesserocr you can specify multiple languages. For example:
import tesserocr
with tesserocr.PyTessBaseAPI(lang='eng+chi_tra') as api:
api.SetImageFile('eSXSz.jpg')
print api.GetUTF8Text()
# or simply
print tesserocr.file_to_text('eSXSz.jpg', lang='eng+chi_tra')
Example output for your image:
In [8]: print tesserocr.file_to_text('eSXSz.jpg', lang='eng+chi_tra')
Character, Chmese 動m川爬d
胸肌岫馴伽 H枷﹏ P﹏… …
〔Manda‥﹝ 二 Standard C…爬虯
一
口
X慣ng怕ng
Note that it's more efficient to initialize the API once as in the first example and re-use it for multiple images by calling SetImageFile (or SetImage with a PIL.Image object) to avoid re-initializing the API every time.

Recognize simple digits with pytesser

I'm learning OCR using PyTesser and Tesseract. As the first milestone, I want to write a tool to recognize captcha that simply consists of some digits. I read some tutorials and wrote such a test program.
from pytesser.pytesser import *
from PIL import Image, ImageFilter, ImageEnhance
im = Image.open("test.tiff")
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
text = image_to_string(im)
print "text={}".format(text)
I tested my code with the image below. But the result is 2(T?770. And I've tested some other similar images as well, in 80% case the results are incorrect.
I'm not familiar with imaging processing. I've two questions here:
Is it possible to tell PyTesser to guess digits only?
I think the image is quite easy for human to read. If it is so difficult for PyTesser to read digits only image, is there any alternatives can do a better OCR?
Any hints are very appreciated.
I think your code is quite okay. It can recognize 207770. The problem is at pytesser installation. The Tesseract in pytesser is out-of-date. You'd download a most recent version and overwrite corresponding files. You'd also edit pytesser.py and change
tesseract_exe_name = 'tesseract'
to
import os.path
tesseract_exe_name = os.path.join(os.path.dirname(__file__), 'tesseract')

python opencv imwrite ... can't find params

I am using opencv with python. I wanted to do an cv2.imwrte:
cv2.imwrite('myimage.png', my_im)
The only problem is that opencv does not recognize the params constants:
cv2.imwrite('myimage.png', my_im, cv2.CV_IMWRITE_PNG_COMPRESSION, 0)
It cannot find CV_IMWRITE_PNG_COMPRESSION at all. Any ideas?
I can't find key CV_XXXXX in the cv2 module:
Try cv2.XXXXX
Failing that, use cv2.cv.CV_XXXXX
In your case, cv2.cv.CV_IMWRITE_PNG_COMPRESSION.
More info.
The docs for OpenCV (cv2 interface) are a bit confusing.
Usually parameters that look like CV_XXXX are actually cv2.XXXX.
I use the following to search for the relevant cv2 constant name. Say I was looking for CV_MORPH_DILATE. I'll search for any constant with MORPH in it:
import cv2
nms = dir(cv2) # list of everything in the cv2 module
[m for m in nms if 'MORPH' in m]
# ['MORPH_BLACKHAT', 'MORPH_CLOSE', 'MORPH_CROSS', 'MORPH_DILATE',
# 'MORPH_ELLIPSE', 'MORPH_ERODE', 'MORPH_GRADIENT', 'MORPH_OPEN',
# 'MORPH_RECT', 'MORPH_TOPHAT']
From this I see that MORPH_DILATE is what I'm looking for.
However, sometimes the constants have not been moved from the cv interface to the cv2 interface yet.
In that case, you can find them under cv2.cv.CV_XXXX.
So, I looked for IMWRITE_PNG_COMPRESSION for you and couldn't find it (under cv2....), and so I looked under cv2.cv.CV_IMWRITE_PNG_COMPRESSION, and hey presto! It's there:
>>> cv2.cv.CV_IMWRITE_PNG_COMPRESSION
16
Expanding on mathematical.coffee to ignore case and look in both namespaces:
import cv2
import cv2.cv as cv
nms = [(n.lower(), n) for n in dir(cv)] # list of everything in the cv module
nms2 = [(n.lower(), n) for n in dir(cv2)] # list of everything in the cv2 module
search = 'imwrite'
print "in cv2\n ",[m[1] for m in nms2 if m[0].find(search.lower())>-1]
print "in cv\n ",[m[1] for m in nms if m[0].find(search.lower())>-1]
>>>
in cv2
['imwrite']
in cv
['CV_IMWRITE_JPEG_QUALITY', 'CV_IMWRITE_PNG_COMPRESSION', 'CV_IMWRITE_PXM_BINARY']
>>>
Hopefully this problem will go away in some later release of cv2...
the compression style is automatically chosen from the file extension. see the cv2.imwrite help here.
however you might still be interested to know all the possible flags used by all the possible functions in cv2 and cv modules.
look for cv2.txt and cv.txt on your computer. they will be where the opencv modules are installed. at the bottom of those text files are a list of the flags used by the respective modules.
just in case you don't find them, you can download the ones i have from here, though they are from august 2011:
cv2.txt
cv.txt
in fact, with cv2 style API, this constant is replaced with cv2.IMWRITE_PNG_COMPRESSION.

Categories