Package: img2table
img2tableimg2tableis a simple, easy to use, table identification and extraction Python Library based onOpenCVimage
processing that supports most common image file formats as well as PDF files.Thanks to its design, it provides a practical and lighter alternative to Neural Networks based solutions, especially for usage on CPU.Table of contentsInstallationFeaturesSupported file formatsUsageDocumentsImagesPDFSupported OCRsTable extractionExcel exportExamplesCaveats / FYIInstallationThe library can be installed via pip:pip install img2table: Standard installation, supporting Tesseractpip install img2table[paddle]: For usage with Paddle OCRpip install img2table[easyocr]: For usage with EasyOCRpip install img2table[gcp]: For usage with Google Vision OCRpip install img2table[aws]: For usage with AWS Textract OCRpip install img2table[azure]: For usage with Azure Cognitive Services OCRFeaturesTable identification for images and PDF files, including bounding boxes at the table cell levelHandling of complex table structures such as merged cellsHandling of implicit rows - seeexampleTable content extraction by providing support for OCR services / toolsExtracted tables are returned as a simple object, including a Pandas DataFrame representationExport extracted tables to an Excel file, preserving their original structureSupported file formatsImagesImages are loaded using theopencv-pythonlibrary, supported formats are listed below.Supported image formatsWindows bitmaps -.bmp,.dibJPEG files -.jpeg,.jpg, *.jpeJPEG 2000 files - *.jp2Portable Network Graphics - *.pngWebP - *.webpPortable image format -.pbm,.pgm,.ppm.pxm, *.pnmPFM files - *.pfmSun rasters -.sr,.rasTIFF files -.tiff,.tifOpenEXR Image files - *.exrRadiance HDR -.hdr,.picRaster and Vector geospatial data supported by GDALOpenCV: Image file reading and writingMulti-page images are not supported.PDFBoth native and scanned PDF files are supported.UsageDocumentsImagesImages are instantiated as follows :fromimg2table.documentimportImageimage=Image(src,detect_rotation=False)Parameterssrc : str,pathlib.Path, bytes orio.BytesIO, requiredImage sourcedetect_rotation : bool, optional, defaultFalseDetect and correct skew/rotation of the imageThe implemented method to handle skewed/rotated images supports skew angles up to 45° and is
based on the publication byHuang, 2020.Setting thedetect_rotationparameter toTrue, image coordinates and bounding boxes returned by other 
methods might not correspond to the original image.PDFPDF files are instantiated as follows :fromimg2table.documentimportPDFpdf=PDF(src,pages=[0,2],detect_rotation=False,pdf_text_extraction=True)Parameterssrc : str,pathlib.Path, bytes orio.BytesIO, requiredPDF sourcepages : list, optional, defaultNoneList of PDF page indexes to be processed. If None, all pages are processeddetect_rotation : bool, optional, defaultFalseDetect and correct skew/rotation of extracted images from the PDFpdf_text_extraction : bool, optional, defaultTrueExtract text from the PDF file for native PDFsPDF pages are converted to images with a 200 DPI for table identification.OCRimg2tableprovides an interface for several OCR services and tools in order to parse table content.If possible (i.e for native PDF), PDF text will be extracted directly from the file and the OCR service/tool will not be called.Tesseractfromimg2table.ocrimportTesseractOCRocr=TesseractOCR(n_threads=1,lang="eng",psm=11,tessdata_dir="...")Parametersn_threads : int, optional, default1Number of concurrent threads used to call Tesseractlang : str, optional, default"eng"Lang parameter used in Tesseract for text extractionpsm : int, optional, default11PSM parameter used in Tesseract, runtesseract --help-psmfor detailstessdata_dir : str, optional, defaultNoneDirectory containing Tesseract traineddata files. If None, theTESSDATA_PREFIXenv variable is used.Usage ofTesseract-OCRrequires prior installation.
Checkdocumentationfor instructions.For Windows users getting environment variable errors, you can check thistutorialPaddleOCRPaddleOCRis an open-source OCR based on Deep Learning models.At first use, relevant languages models will be downloaded.fromimg2table.ocrimportPaddleOCRocr=PaddleOCR(lang="en",kw={"kwarg":kw_value,...})Parameterslang : str, optional, default"en"Lang parameter used in Paddle for text extraction, checkdocumentation for available languageskw : dict, optional, defaultNoneDictionary containing additional keyword arguments passed to the PaddleOCR constructor.NB:For usage of PaddleOCR with GPU, the CUDA specific version of paddlepaddle-gpu has to be installed by the user manually 
as stated in thisissue.# Example of installation with CUDA 11.8pipinstallpaddlepaddle-gpu==2.5.0rc1.post118-fhttps://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html
pipinstallpaddleocrimg2tableIf you get an error trying to run PaddleOCR on Ubuntu,
please check thisissuefor a working solution.EasyOCREasyOCRis an open-source OCR based on Deep Learning models.At first use, relevant languages models will be downloaded.fromimg2table.ocrimportEasyOCRocr=EasyOCR(lang=["en"],kw={"kwarg":kw_value,...})Parameterslang : list, optional, default["en"]Lang parameter used in EasyOCR for text extraction, checkdocumentation for available languageskw : dict, optional, defaultNoneDictionary containing additional keyword arguments passed to the EasyOCRReaderconstructor.docTRdocTRis an open-source OCR based on Deep Learning models.In order to be used, docTR has to be installed by the user beforehand. Installation procedures are detailed in
the package documentationfromimg2table.ocrimportDocTRocr=DocTR(detect_language=False,kw={"kwarg":kw_value,...})Parametersdetect_language : bool, optional, defaultFalseParameter indicating if language prediction is run on the documentkw : dict, optional, defaultNoneDictionary containing additional keyword arguments passed to the docTRocr_predictormethod.Google VisionAuthentication to GCP can be done by setting the standardGOOGLE_APPLICATION_CREDENTIALSenvironment variable.If this variable is missing, an API key should be provided via theapi_keyparameter.fromimg2table.ocrimportVisionOCRocr=VisionOCR(api_key="api_key",timeout=15)Parametersapi_key : str, optional, defaultNoneGoogle Vision API keytimeout : int, optional, default15API requests timeout, in secondsAWS TextractWhen using AWS Textract, the DetectDocumentText API is exclusively called.Authentication to AWS can be done by passing credentials to theTextractOCRclass.If credentials are not provided, authentication is done using environment variables or configuration files.
Checkboto3documentationfor more details.fromimg2table.ocrimportTextractOCRocr=TextractOCR(aws_access_key_id="***",aws_secret_access_key="***",aws_session_token="***",region="eu-west-1")Parametersaws_access_key_id : str, optional, defaultNoneAWS access key idaws_secret_access_key : str, optional, defaultNoneAWS secret access keyaws_session_token : str, optional, defaultNoneAWS temporary session tokenregion : str, optional, defaultNoneAWS server regionAzure Cognitive Servicesfromimg2table.ocrimportAzureOCRocr=AzureOCR(endpoint="abc.azure.com",subscription_key="***")Parametersendpoint : str, optional, defaultNoneAzure Cognitive Services endpoint. If None, inferred from theCOMPUTER_VISION_ENDPOINTenvironment variable.subscription_key : str, optional, defaultNoneAzure Cognitive Services subscription key. If None, inferred from theCOMPUTER_VISION_SUBSCRIPTION_KEYenvironment variable.Table extractionMultiple tables can be extracted at once from a PDF page/ an image using theextract_tablesmethod of a document.fromimg2table.ocrimportTesseractOCRfromimg2table.documentimportImage# Instantiation of OCRocr=TesseractOCR(n_threads=1,lang="eng")# Instantiation of document, either an image or a PDFdoc=Image(src)# Table extractionextracted_tables=doc.extract_tables(ocr=ocr,implicit_rows=False,borderless_tables=False,min_confidence=50)Parametersocr : OCRInstance, optional, defaultNoneOCR instance used to parse document text. If None, cells content will not be extractedimplicit_rows : bool, optional, defaultFalseBoolean indicating if implicit rows should be identified - check relatedexampleborderless_tables : bool, optional, defaultFalseBoolean indicating ifborderless tablesare extractedon top ofbordered tables.min_confidence : int, optional, default50Minimum confidence level from OCR in order to process text, from 0 (worst) to 99 (best)NB: Borderless table extraction can, by design, only extract tables with 3 or more columns.Method returnTheExtractedTableclass is used to model extracted tables from documents.Attributesbbox :BBoxTable bounding boxtitle : strExtracted title of the tablecontent :OrderedDictDict with row indexes as keys and list ofTableCellobjects as valuesdf :pd.DataFramePandas DataFrame representation of the tablehtml :strHTML representation of the tableIn order to access bounding boxes at the cell level, you can use the following code snippet :forid_row,rowinenumerate(table.content.values()):forid_col,cellinenumerate(row):x1=cell.bbox.x1y1=cell.bbox.y1x2=cell.bbox.x2y2=cell.bbox.y2value=cell.valueImagesextract_tablesmethod from theImageclass returns a list ofExtractedTableobjects.output=[ExtractedTable(...),ExtractedTable(...),...]PDFextract_tablesmethod from thePDFclass returns anOrderedDictobject with page indexes as keys and lists ofExtractedTableobjects.output={0:[ExtractedTable(...),...],1:[],...last_page:[ExtractedTable(...),...]}Excel exportTables extracted from a document can be exported to a xlsx file. The resulting file is composed of one worksheet per extracted table.Method arguments are mostly common with theextract_tablesmethod.fromimg2table.ocrimportTesseractOCRfromimg2table.documentimportImage# Instantiation of OCRocr=TesseractOCR(n_threads=1,lang="eng")# Instantiation of document, either an image or a PDFdoc=Image(src)# Extraction of tables and creation of a xlsx file containing tablesdoc.to_xlsx(dest=dest,ocr=ocr,implicit_rows=False,borderless_tables=False,min_confidence=50)Parametersdest : str,pathlib.Pathorio.BytesIO, requiredDestination for xlsx fileocr : OCRInstance, optional, defaultNoneOCR instance used to parse document text. If None, cells content will not be extractedimplicit_rows : bool, optional, defaultFalseBoolean indicating if implicit rows should be identified - check relatedexampleborderless_tables : bool, optional, defaultFalseBoolean indicating ifborderless tablesare extracted. It requires to provide an OCR to the method in order to be performed -feature in alpha versionmin_confidence : int, optional, default50Minimum confidence level from OCR in order to process text, from 0 (worst) to 99 (best)ReturnsIf aio.BytesIObuffer is passed as dest arg, it is returned containing xlsx dataExamplesSeveral Jupyter notebooks with examples are available :Basic usage: generic library usage, including examples with images, PDF and OCRsBorderless tables: specific examples dedicated to the extraction of borderless tablesImplicit rows: illustrated effect 
of the parameterimplicit_rowsof theextract_tablesmethodCaveats / FYIFor table extraction, results are highly dependent on OCR quality. By design, tables where no OCR data 
can be found are not returned.The library is tailored for usage on documents with white/light background. 
Effectiveness can not be guaranteed on other type of documents.Table detection using only OpenCV processing can have some limitations. If the library fails to detect tables, 
you may check CNN based solutions likeCascadeTabNetor 
thePaddleOCR implementation.