首先下载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);
}