首先下載tessnet2_32.dll及相關語言包,將dll加入引用
- private tessnet2.Tesseract ocr = new tessnet2.Tesseract();//聲明一個OCR類
- //程序開始的時候,初始化OCR
- ocr.SetVariable("tessedit_char_whitelist", "0123456789."); //設置識別變量,當前只能識別數字。
- ocr.Init(@"D:\tessdata", "eng", false); //應用當前語言包。注,Tessnet2是支持多國語的。語言包下載鏈接:http://code.google.com/p/tesseract-ocr/downloads/list
- //下邊這個函數是將網絡上的圖片識別成字符串,傳入圖片的超鏈接,輸出字符串
- public string Bmp2Str(string bmpurl)
- {
- //http://www.newwhy.com/2010/0910/13708.html
- string s = "0";
- WebClient wc = new WebClient();
- try
- {
- byte[] oimg = wc.DownloadData(bmpurl);//將要識別的圖像下載下來
- MemoryStream ms = new MemoryStream(oimg);
- Bitmap image = new Bitmap(ms);
- //為了提高識別率,所以對圖片進行簡單的處理
- image = BlackAndWhite(image, 0.8);//黑白處理,這個函數看下邊
- image = new Bitmap(image, image.Width * 3, image.Height * 3);//放大三倍
- Monitor.Enter(this);//因為是多線程,所以用到了Monitor。
- System.Collections.Generic.List<tessnet2.Word> result = ocr.DoOCR(image, Rectangle.Empty);//執行識別操作
- foreach (tessnet2.Word word in result) //遍歷識別結果。
- s = s + word.Text;
- Monitor.Exit(this);
- if (s.Length > 2)
- s = s.Substring(2, s.Length - 2);
- }
- catch
- {
- s = "0";
- }
- finally
- {
- wc.Dispose();
- }
- return s;
- //Console.WriteLine("{0} : {1}", word.Confidence, word.Text);
- }
- //黑白處理的函數,網上查的。
- public static Bitmap BlackAndWhite(Bitmap bitmap, Double hsb)
- {
- if (bitmap == null)
- {
- return null;
- }
- int width = bitmap.Width;
- int height = bitmap.Height;
- try
- {
- Bitmap bmpReturn = new Bitmap(width, height, PixelFormat.Format1bppIndexed);
- BitmapData srcBits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
- BitmapData targetBits = bmpReturn.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
- unsafe
- {
- byte* pSrcBits = (byte*)srcBits.Scan0.ToPointer();
- for (int h = 0; h < height; h++)
- {
- byte[] scan = new byte[(width + 7) / 8];
- for (int w = 0; w < width; w++)
- {
- int r, g, b;
- r = pSrcBits[2];
- g = pSrcBits[1];
- b = pSrcBits[0];
- if (GetBrightness(r, g, b) >= hsb) scan[w / 8] |= (byte)(0x80 >> (w % 8));
- pSrcBits += 3;
- }
- Marshal.Copy(scan, 0, (IntPtr)((int)targetBits.Scan0 + targetBits.Stride * h), scan.Length);
- pSrcBits += srcBits.Stride - width * 3;
- }
- bmpReturn.UnlockBits(targetBits);
- bitmap.UnlockBits(srcBits);
- return bmpReturn;
- }
- }
- catch
- {
- return null;
- }
- }
找到了
private static float GetBrightness(int r, int g, int b)
{
float fR = ((float)r) / 255f;
float fG = ((float)g) / 255f;
float fB = ((float)b) / 255f;
float fMax = fR;
float fMin = fR;
fMax = (fG > fMax) ? fG : fMax;
fMax = (fB > fMax) ? fB : fMax;
fMin = (fG < fMax) ? fG : fMax;
fMin = (fB < fMax) ? fB : fMax;
return ((fMax + fMin) / 2f);
}