Package: ocrd-fork-tesserocr
A simple,Pillow-friendly,
wrapper around thetesseract-ocrAPI for Optical Character Recognition
(OCR).tesserocrintegrates directly with Tesseract’s C++ API using Cython
which allows for a simple Pythonic and easy-to-read source code. It
enables real concurrent execution when used with Python’sthreadingmodule by releasing the GIL while processing an image in tesseract.tesserocris designed to bePillow-friendly but can also be used
with image files instead.RequirementsRequires libtesseract (>=3.04) and libleptonica (>=1.71).On Debian/Ubuntu:$ apt-get install tesseract-ocr libtesseract-dev libleptonica-dev pkg-configYou may need tomanually compile tesseractfor a more recent version. Note that you may need
to update yourLD_LIBRARY_PATHenvironment variable to point to the right library versions in
case you have multiple tesseract/leptonica installations.Cython(>=0.23) is required for building and optionallyPillowto supportPIL.Imageobjects.InstallationLinux and BSD/MacOS$ pip install tesserocrThe setup script attempts to detect the include/library dirs (viapkg-configif available) but you
can override them with your own parameters, e.g.:$ CPPFLAGS=-I/usr/local/include pip install tesserocror$ python setup.py build_ext -I/usr/local/includeTested on Linux and BSD/MacOSWindowsThe proposed downloads consist of stand-alone packages containing all the Windows libraries needed for execution. This means that no additional installation of tesseract is required on your system.CondaYou can use the channelsimonflueckigerto install from Conda:> conda install -c simonflueckiger tesserocror to gettesserocrcompiled withtesseract 4.0.0:> conda install -c simonflueckiger/label/tesseract-4.0.0-master tesserocrpipDownload the wheel file corresponding to your Windows platform and Python installation fromsimonflueckiger/tesserocr-windows_build/releasesand install them via:> pip install <package_name>.whlUsageInitialize and re-use the tesseract API instance to score multiple
images:fromtesserocrimportPyTessBaseAPIimages=['sample.jpg','sample2.jpg','sample3.jpg']withPyTessBaseAPI()asapi:forimginimages:api.SetImageFile(img)print(api.GetUTF8Text())print(api.AllWordConfidences())# api is automatically finalized when used in a with-statement (context manager).# otherwise api.End() should be explicitly called when it's no longer needed.PyTessBaseAPIexposes several tesseract API methods. Make sure you
read their docstrings for more info.Basic example using available helper functions:importtesserocrfromPILimportImageprint(tesserocr.tesseract_version())# print tesseract-ocr versionprint(tesserocr.get_languages())# prints tessdata path and list of available languagesimage=Image.open('sample.jpg')print(tesserocr.image_to_text(image))# print ocr text from image# orprint(tesserocr.file_to_text('sample.jpg'))image_to_textandfile_to_textcan be used withthreadingto
concurrently process multiple images which is highly efficient.Advanced API ExamplesGetComponentImages example:fromPILimportImagefromtesserocrimportPyTessBaseAPI,RILimage=Image.open('/usr/src/tesseract/testing/phototest.tif')withPyTessBaseAPI()asapi:api.SetImage(image)boxes=api.GetComponentImages(RIL.TEXTLINE,True)print('Found{}textline image components.'.format(len(boxes)))fori,(im,box,_,_)inenumerate(boxes):# im is a PIL image object# box is a dict with x, y, w and h keysapi.SetRectangle(box['x'],box['y'],box['w'],box['h'])ocrResult=api.GetUTF8Text()conf=api.MeanTextConf()print(u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, ""confidence:{1}, text:{2}".format(i,conf,ocrResult,**box))Orientation and script detection (OSD):fromPILimportImagefromtesserocrimportPyTessBaseAPI,PSMwithPyTessBaseAPI(psm=PSM.AUTO_OSD)asapi:image=Image.open("/usr/src/tesseract/testing/eurotext.tif")api.SetImage(image)api.Recognize()it=api.AnalyseLayout()orientation,direction,order,deskew_angle=it.Orientation()print("Orientation:{:d}".format(orientation))print("WritingDirection:{:d}".format(direction))print("TextlineOrder:{:d}".format(order))print("Deskew angle:{:.4f}".format(deskew_angle))or more simply withOSD_ONLYpage segmentation mode:fromtesserocrimportPyTessBaseAPI,PSMwithPyTessBaseAPI(psm=PSM.OSD_ONLY)asapi:api.SetImageFile("/usr/src/tesseract/testing/eurotext.tif")os=api.DetectOS()print("Orientation:{orientation}\nOrientation confidence:{oconfidence}\n""Script:{script}\nScript confidence:{sconfidence}".format(**os))more human-readable info with tesseract 4+ (demonstrates LSTM engine usage):fromtesserocrimportPyTessBaseAPI,PSM,OEMwithPyTessBaseAPI(psm=PSM.OSD_ONLY,oem=OEM.LSTM_ONLY)asapi:api.SetImageFile("/usr/src/tesseract/testing/eurotext.tif")os=api.DetectOrientationScript()print("Orientation:{orient_deg}\nOrientation confidence:{orient_conf}\n""Script:{script_name}\nScript confidence:{script_conf}".format(**os))Iterator over the classifier choices for a single symbol:from__future__importprint_functionfromtesserocrimportPyTessBaseAPI,RIL,iterate_levelwithPyTessBaseAPI()asapi:api.SetImageFile('/usr/src/tesseract/testing/phototest.tif')api.SetVariable("save_blob_choices","T")api.SetRectangle(37,228,548,31)api.Recognize()ri=api.GetIterator()level=RIL.SYMBOLforriniterate_level(ri,level):symbol=r.GetUTF8Text(level)# r == riconf=r.Confidence(level)ifsymbol:print(u'symbol{}, conf:{}'.format(symbol,conf),end='')indent=Falseci=r.GetChoiceIterator()forcinci:ifindent:print('\t\t',end='')print('\t- ',end='')choice=c.GetUTF8Text()# c == ciprint(u'{}conf:{}'.format(choice,c.Confidence()))indent=Trueprint('---------------------------------------------')