.NET ez 2012-06-20
OCR 全名為「Optical Character Recognition」,即是「光學字元辨識」的意思。
本文利用 Microsoft Office Document Imaging (MODI) 製作 光學字元辨識(OCR) 首先必須先安裝Microsoft Office Document Imaging (MODI),請使用Office 2003 或 Office 2007 安裝光碟才有內建此元件,記住Office 2010未包含此元件喔!
如果沒有Office光碟片,也可以下載 SharePoint Designer 2007 裡面也有內建MODI。
SharePoint Designer 2007
下載網址:http://www.microsoft.com/downloads/zh-tw/details.aspx?FamilyID=BAA3AD86-BFC1-4BD4-9812-D9E710D44F42
安裝方式: 放入Office光碟進行安裝,選擇自訂安裝,並且依照底下框選項目進行選擇。
開發方式: 將COM元件 Microsoft Office Document Imaging xx.0 Type Library 加入參考。
範例程式碼:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace OCR
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "*.jpg;*.gif;*.png;*.bmp|*.jpg;*.gif;*.png;*.bmp";
if (OFD.ShowDialog() == DialogResult.OK)
{
label1.Text = "辨識結果:" + OCR(OFD.FileName);
pictureBox1.Image = Bitmap.FromFile(OFD.FileName);
}
}
private string OCR(string fileroute)
{
string str = string.Empty;
try
{
//檢查尺寸是否太小,如果圖片過小,會造成MODI當掉
bool Allow = false;
using (Bitmap bm = (Bitmap)Bitmap.FromFile(fileroute))
{
//長寬需大於30才執行
if (bm.Width >= 30 && bm.Height >= 30) Allow = true;
bm.Dispose();
}
if (Allow)
{
MODI.Document MODI_Document = new MODI.Document();
MODI_Document.Create(fileroute);
MODI.Image MODI_Image = (MODI.Image)MODI_Document.Images[0];
MODI_Image.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
//辨識結果
foreach (MODI.Word word in MODI_Image.Layout.Words) str += word.Text + " ";
MODI_Document.Close();
}
}
catch { }
return str;
}
}
}標籤: .NET
