Export OCR Results to JSON - Python

This tutorial shows how to OCR an image and export the results to a JSON file in a Python application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to save OCR results to a JSON file in a Python Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (1 KB)
Platform Python Console Application
IDE Visual Studio 2022
Runtime Target Python 3.10 or higher
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Export OCR Results to JSON - Python tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in one the following topic: * Add References and Set a License for Python.

If you do not have that project, follow the steps in the relevant tutorial to create it.

The references needed depend upon the purpose of the project.

This tutorial requires the following .NET DLLs:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Initialize the OcrEngine

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, open Project-Name.py and place the following references below the "Add references to LEADTOOLS" comment

# Add references to LEADTOOLS 
from leadtools import LibraryLoader 
LibraryLoader.add_reference("Leadtools") 
from Leadtools import * 
LibraryLoader.add_reference("Leadtools.Ocr") 
from Leadtools.Ocr import * 
LibraryLoader.add_reference("Leadtools.Document") 
from Leadtools.Document import * 
LibraryLoader.add_reference("Newtonsoft.Json") 
from Newtonsoft.Json import * 
 
from System.IO import * 
from System.Collections.Generic import * 

Add a new method called init_ocr_engine() to return the IOcrEngine and call it inside the main() method after the SetLicense() method call, as shown below.

def main(): 
     
    Support.set_license(os.path.join(DemosTools.get_root(), "C:/LEADTOOLS22/Support/Common/License")) 
 
    file = r"C:\LEADTOOLS22\Resources\Images\leadtools.pdf" 
    ocr_engine = init_ocr_engine() 
    ocr_and_save_results(ocr_engine, file)   

Add the below code to the init_ocr_engine() method to initialize the IOcrEngine.

def init_ocr_engine(): 
     
    ocr_engine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD) 
    ocr_engine.Startup(None, None, None, r"C:\LEADTOOLS22\Bin\Common\OcrLEADRuntime") 
    return ocr_engine 

Add the Text Recognition and Export to JSON Code

Create a new method in the Project-Name.py file named ocr_and_save_results(ocr_engine, file) and call it in the main() method after the ocr_engine = init_ocr_engine(); line of code. Add the code below to the ocr_and_save_results() method to OCR the PDF document and export the recognition results to a JSON file.

def ocr_and_save_results(ocr_engine, file): 
 
    doc_options = LoadDocumentOptions() 
    doc_options.FirstPageNumber = 1 
    doc_options.LastPageNumber = -1 
 
    document = DocumentFactory.LoadFromFile(file, doc_options) 
    document.Text.OcrEngine = ocr_engine 
 
    document_page_texts = List[DocumentPageText]() 
 
    for page in document.Pages: 
        # parse the text and build the DocumentPageText object 
        page_text = page.GetText()    
        page_text.BuildText() 
        page_text.BuildWords() 
        document_page_texts.Add(page_text) 
 
    # Save the recognized words to JSON 
    json = JsonConvert.SerializeObject(document_page_texts, Formatting.Indented) 
    json_path = Path.ChangeExtension(file, ".json") 
 
    File.WriteAllText(json_path, json) 

Handling Streams

Alternatively, you could use memory stream to handle the document. To do that, add the following code into the program and call this method in the main() method:

def ocr_stream_and_save_results(ocr_engine): 
    filename = Path.Combine(r"C:\LEADTOOLS22\Resources\Images", "Leadtools.pdf") 
    stream = File.OpenRead(filename) 
    options = LoadDocumentOptions() 
    document = DocumentFactory.LoadFromStream(stream, options) 
    document.Text.OcrEngine = ocr_engine 
    print("Doc loaded") 
     
    document_page_texts = List[DocumentPageText]() 
 
    for page in document.Pages: 
        # Parse the text and build the DocumentPageText object 
        page_text = page.GetText()    
        page_text.BuildText() 
        page_text.BuildWords() 
        document_page_texts.Add(page_text) 
    # Save the recognized words to JSON 
    json = JsonConvert.SerializeObject(document_page_texts, Formatting.Indented) 
    json_path = Path.ChangeExtension(filename, ".json") 
 
    File.WriteAllText(json_path, json) 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the application will OCR a document and create a JSON containing the recognition results. For the purposes of this tutorial, we used the PDF file located here: <INSTALL_DIR>\LEADTOOLS22\Resources\Images\leadtools.pdf

Download the resulting JSON here.

Wrap-up

This tutorial showed how to run OCR on a document and export the results to JSON. Also, it covered how to use the IOcrEngine interface, along with the LEADDocument, DocumentPage and DocumentPageText classes.

See Also

Help Version 22.0.2024.3.20
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.