DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • DGS GraphQL and Spring Boot
  • Auto-Instrumentation in Azure Application Insights With AKS
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Trending

  • Agile’s Quarter-Century Crisis
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  • Advancing Robot Vision and Control

How to Extract Text From Part of an Image inside .NET Applications

By 
David Zondray user avatar
David Zondray
·
Jul. 16, 14 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
4.8K Views

Join the DZone community and get the full member experience.

Join For Free
This technical tip shows how to extract text from part of an image inside .NET Applications. Aspose.OCR for .NET provides OcrEngine class to extract text from a specific part of the image document. The OcrEngine class requires Source image, Language and Resource file for character recognition. The source image is the document on which OCR will be performed. The image can be a BMP, TIFF, JPEG, GIF or PNG file. The OcrEngine.Image property is used to set the source image. One or more languages must be specified before performing OCR. This is because the OcrEngine tries to recognize characters of the specified languages in the image. The OcrEngine recognizes text word by word. Each recognized word has a specific language which might be different from the language of the other words. Aspose.OCR for .NET also maintains the priority of each language. The language added first has the highest priority. Each language added afterwards has lower priority: the last added language has the least priority.  The language priority matters when OCR is performed. Aspose.OCR for .NET first attempts to read characters as the highest priority language. If it doesn't recognize them, it tries to read them in the next language. If a word is identical in two or more languages, the OcrEngine assigns the highest priority language to the recognized word.  The resource file is a ZIP archive that contains the data necessary to perform OCR. The OcrEngine.Resource property must be set and point to the resource file before starting an OCR process.

To run OCR on an image using the OcrEngine class:

  • Create an instance of OcrEngine and initialize it using the default constructor.
  • Set the image file using the OcrEngine.Image property.
  • Add language(s) using the OcrEngine.Languages.AddLanguage method.
  • Set the start point, width and height of the recognition block using the OcrConfig.AddRecognitionBlock method.
  • Set the resource file using the OcrEngine.Resource property.
  • Call the OcrEngine.Process method to perform OCR on the whole image.
  • If OcrEngine.Process returns true, then get the recognized text with the IRecognitionBlock.Text property.
//The sample code below shows how to use the steps above to run OCR on part of an image. 

//[C#]

const string resourceFileName = @"Aspose.OCR.Resources.zip";

try
{
    //Create an instance of OcrEngine and assign 
    //image, language and image settings
    OcrEngine ocrEngine = new OcrEngine();
    ocrEngine.Image = ImageStream.FromFile("Sample.bmp");

    ocrEngine.Languages.AddLanguage(Language.Load("english"));
    ocrEngine.Config.UseDefaultDictionaries = true;

    //Define the block in which to recognize text
    int startX = 0, startY = 0, width = 120, height = 100;

    //Clear recognition blocks
    ocrEngine.Config.ClearRecognitionBlocks();

    //Add 3 rectangle blocks to user defined recognition blocks
    ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(startX, startY, width, height));

    //Set the resource file name and extract OCR text
    using (ocrEngine.Resource = new FileStream(resourceFileName, FileMode.Open))
    {
        try
        {
            if (ocrEngine.Process())
            {
                //Retrieve user defined blocks that determines the paye layout
                var blocks = ocrEngine.Config.RecognitionBlocks;
                //Loop over the list of blocks
                foreach (var block in blocks)
                {
                    //Display if block is set to be recognized
                    Console.WriteLine(block.ToRecognize);
                    //Check if block has recognition data
                    if (block.RecognitionData == null)
                    {
                        Console.WriteLine("Null{0}", Environment.NewLine);
                        continue;
                    }
                    //Display dimension & size of rectangle that defines the recognition block
                    Console.WriteLine("Block: {0}", block.Rectangle);
                    //Display the recognition results
                    Console.WriteLine("Text: {0}{1}", block.RecognitionData.Text, Environment.NewLine);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
    ocrEngine = null;
}
catch (Exception ex)
{
    Console.WriteLine("Exception: " + ex.Message);
} 
 

//[VB.NET]
 
Const resourceFileName As String = "Aspose.OCR.Resources.zip"

Try
	'Create an instance of OcrEngine and assign 
	'image, language and image settings
	Dim ocrEngine As New OcrEngine()
	ocrEngine.Image = ImageStream.FromFile("Sample.bmp")

	ocrEngine.Languages.AddLanguage(Language.Load("english"))
	ocrEngine.Config.UseDefaultDictionaries = True

	'Define the block in which to recognize text
	Dim startX As Integer = 0, startY As Integer = 0, width As Integer = 120, height As Integer = 100

	'Clear recognition blocks
	ocrEngine.Config.ClearRecognitionBlocks()

	'Add 3 rectangle blocks to user defined recognition blocks
	ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(startX, startY, width, height))

	'Set the resource file name and extract OCR text
	ocrEngine.Resource = New FileStream(resourceFileName, FileMode.Open)
	Using ocrEngine.Resource
		Try
			If ocrEngine.Process() Then
				'Retrieve user defined blocks that determines the paye layout
				Dim blocks = ocrEngine.Config.RecognitionBlocks
				'Loop over the list of blocks
				For Each block In blocks
					'Display if block is set to be recognized
					Console.WriteLine(block.ToRecognize)
					'Check if block has recognition data
					If block.RecognitionData Is Nothing Then
						Console.WriteLine("Null{0}", Environment.NewLine)
						Continue For
					End If
					'Display dimension & size of rectangle that defines the recognition block
					Console.WriteLine("Block: {0}", block.Rectangle)
					'Display the recognition results
					Console.WriteLine("Text: {0}{1}", block.RecognitionData.Text, Environment.NewLine)
				Next block
			End If
		Catch ex As Exception
			Console.WriteLine("Exception: " & ex.Message)
		End Try
	End Using
	ocrEngine = Nothing
Catch ex As Exception
	Console.WriteLine("Exception: " & ex.Message)
End Try

application Extract

Opinions expressed by DZone contributors are their own.

Related

  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • DGS GraphQL and Spring Boot
  • Auto-Instrumentation in Azure Application Insights With AKS
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!