110,561
社区成员
发帖
与我相关
我的任务
分享
//引用 ITPUB个人空间
程序使用Tesseract进行图片识别,其.NET版本地址为:http://www.pixel-technology.com/freeware/tessnet2/
private void btnGo_Click(objectsender, EventArgs e)
{
tessnet2.Tesseractocr=newtessnet2.Tesseract();//声明一个OCR类
string defaultCharList="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-";
if(!string.IsNullOrEmpty(txtCharList.Text))
{
defaultCharList=txtCharList.Text;
}
ocr.SetVariable("tessedit_char_whitelist", defaultCharList);//设置识别变量,当前只能识别数字及英文字符。
ocr.Init(Application.StartupPath+@"\tessdata","eng",false);//应用当前语言包。注,Tessnet2是支持多国语的。语言包下载链接:http://code.google.com/p/tesseract-ocr/downloads/list
WebClient wc=newWebClient();
byte[] oimg=wc.DownloadData(txtImageUrl.Text);// 自己修改成要识别的地址吧
Bitmap bp=newBitmap(newMemoryStream(oimg),true);//识别图像
Bitmap bp2=newBitmap(newMemoryStream(oimg),true);
picBox1.Image=bp2;
//bp = ImageProcess.RemoveGreen(bp);
//bp = ImageProcess.ToBW(bp);
picBox2.Image=bp;
List<tessnet2.Word>result=newList<tessnet2.Word>();
stringtxt="";
try
{
result=ocr.DoOCR(bp, Rectangle.Empty);//执行识别操作
foreach(tessnet2.Wordwordinresult)//遍历识别结果。
{
txt+=word.Text;
}
}
catch(Exception ex)
{
}
if(string.IsNullOrEmpty(txt)||txt=="~")
{
#region 如图片太小,无法识别,则先放大
intw=bp.Width>=100?bp.Width:100;
inth=bp.Height>=30?bp.Height:30;
Bitmap resizedBmp=newBitmap(w, h);
Graphics g=Graphics.FromImage(resizedBmp);
g.DrawImage(bp,newRectangle(0,0, w, h),newRectangle(0,0, bp.Width, bp.Height), GraphicsUnit.Pixel);
bp=resizedBmp;
#endregion
picBox2.Image=bp;
result=ocr.DoOCR(bp, Rectangle.Empty);//执行识别操作
txt="";
foreach(tessnet2.Wordwordinresult)//遍历识别结果。
{
txt+=word.Text;
}
}
textBox1.Text=txt;
}