2009年11月20日 星期五

[C#] OCR 文字判讀

感覺準確度不高阿。。真是頭痛 ><" using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Imaging; namespace _20091117_OCR_TEST { public partial class Form1 : Form { // 宣告 OpenFileDialog 控制項,並且實例化 OpenFileDialog OFD = new OpenFileDialog(); public Form1() { InitializeComponent(); this.Text = ""; } //OCR 辨識文字 private string Recognition(string strFileName) { string strResult = string.Empty; // 宣告 MODI.Document 物件 modiDocument,並且實例化 MODI.Document modiDocument = new MODI.Document(); // MODI.Document 創建 modiDocument.Create(strFileName); // 宣告 MODI.Image 物件 modiImage,其內容值來自 MODI.Document 物件 modiDocument MODI.Image modiImage = (MODI.Image)modiDocument.Images[0]; // OCR Method(Language, WithAutoRotation, WithStraightenImage) modiImage.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false); // 組合 OCR 辨識後的 Word foreach (MODI.Word WordItem in modiImage.Layout.Words) { strResult += WordItem.Text + " "; } modiDocument.Close(false); // 回傳辨識結果 return strResult; } //當按下 PICTURE 時 private void pictureBox1_Click_1(object sender, EventArgs e) { CALL_LOAD_PICTURE(); } //讀取 圖片並顯示出來(原始圖檔) private void CALL_LOAD_PICTURE() { this.Text = ""; pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; // 加入檔案過濾條件 OFD.Filter = "*.jpg;*.png;*.bmp|*.jpg;*.png;*.bmp"; if (OFD.ShowDialog() == DialogResult.OK) { // 讓 pictureBox1.Image 為選擇的圖檔 this.pictureBox1.Image = Image.FromFile(OFD.FileName); // 顯示辨識結果 string aa = Recognition(OFD.FileName).ToString().Replace(" ", "").Replace("-", "").Replace(".", ""); int cc = aa.IndexOf("FT"); this.Text = "判讀結果:" + aa.Substring(cc).ToString(); } } private void 轉換灰階並再次判讀ToolStripMenuItem_Click(object sender, EventArgs e) { if (OFD.FileName.Length > 1)
{
try
{
//並宣告bm1為Bitmap
Bitmap bm1 = (Bitmap)pictureBox1.Image;
//宣告寬及高
int w1 = pictureBox1.Image.Width;
int h1 = pictureBox1.Image.Height;
int x;
int y;
//掃影像每一個pixel並做處理
for (y = 0; y <= h1 - 1; y++)
{
for (x = 0; x <= w1 - 1; x++)
{
Color c1 = bm1.GetPixel(x, y);
int r1 = c1.R;
int g1 = c1.G;
int b1 = c1.B;
int avg1 = (r1 + g1 + b1) / 4;
bm1.SetPixel(x, y, Color.FromArgb(avg1, avg1, avg1));
}
}
//處理完後放回pictureBox1
pictureBox1.Image = bm1;

//存圖片
string buff_path = Application.ExecutablePath.ToString() + "-buff.bmp";
pictureBox1.Image.Save(Application.ExecutablePath + "-buff.bmp");

// 顯示辨識結果
string aa = Recognition(buff_path).ToString().Replace(" ", "").Replace("-", "").Replace(".", "");
int cc = aa.IndexOf("FT");
this.Text = "灰階 判讀結果:" + aa.Substring(cc).ToString();
}

catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}
}
}
}

沒有留言:

張貼留言