Sunday, September 14, 2014

OCR with c#


This blog shows how to perform Optical character recognition (ocr) with c# for that we need a tessnet2 .net assembly. It is a c# wrapper class of the tesseract that exposes very simple methods to do ocr.

Input Image:

Output Image:

Source Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace TessnetOcr
{
public partial class Form1 : Form
{
Bitmap Binput;


public Form1()

{
InitializeComponent();
comboBox1.SelectedIndex = 0;
}

private void button1_Click(object sender, EventArgs e)
{
openDialog();
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)

{
openDialog();
}

private void openDialog()
{
try

{
ImageFileDialog.FileName = "";
ImageFileDialog.Filter = "Jpeg Files|*.jpg|Tiff Files|*.tiff";

DialogResult result = ImageFileDialog.ShowDialog();


if (result == DialogResult.OK)

{
filepath.Text = ImageFileDialog.FileName;
Binput = new
Bitmap(filepath.Text);

pictureBox1.Image = Binput;
}
}
catch (Exception exception)
{
MessageBox.Show("Select the image with proper extension" + exception);
}
}

private void button2_Click(object sender, EventArgs e)

{
try

{
tessnet2.Tesseract tessnet = new tessnet2.Tesseract();
tessnet.Init(@"tessdata","eng",false);
List<tessnet2.Word> result = tessnet.DoOCR(Binput, Rectangle.Empty);

foreach (tessnet2.Word word in result)

{
textBox2.Text = textBox2.Text + word.Text + " ";
}
MessageBox.Show("Conversion Done sucessfully...");
}
catch (Exception exception)
{
MessageBox.Show("Problem in converting" + exception);
}
}

private void button3_Click(object sender, EventArgs e)
{
try

{
saveFileDialog1.Filter = "Text files|*.txt|MS-Word|*.doc|Wordpad|*.RTF";
saveFileDialog1.FileName = String.Empty;

DialogResult result = saveFileDialog1.ShowDialog();


if (result == DialogResult.OK)

{

FileStream fileStream = new
FileStream(saveFileDialog1.FileName, FileMode.Create);

using (StreamWriter streamWriter = new
StreamWriter(fileStream))

{
streamWriter.Write(textBox2.Text);
}
MessageBox.Show("Saved Sucessfully...");
}
}

catch (Exception exception)

{
MessageBox.Show("File Cannot be created" + exception);
}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

 

Download the zipped source code form here.

Click here for my previous blog.

Happy Coding. 

 


 


1 comment: