- private tessnet2.Tesseract ocr = new tessnet2.Tesseract();
-
-
-
- ocr.SetVariable("tessedit_char_whitelist", "0123456789.");
- ocr.Init(@"D:\tessdata", "eng", false);
-
-
-
-
- public string Bmp2Str(string bmpurl)
-
- {
-
- 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);
- 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;
-
-
-
- }
-
-
-
-
-
-
-
- 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);
}