此种方法用的是百度接口,效果是可以,但是免费版一个月有使用上限,并且只能识别中英文,要想一直免费使用,突破使用次数,并且能识别韩日等其他语言的,可以参考我另一篇博客:C#用Tesseract进行OCR识别,可识别中英日韩所有语言
源码地址:https://download.csdn.net/download/horseroll/10922450
无积分付费下载地址:https://download.csdn.net/download/HorseRoll/21113070
使用效果:
1.首先先引用AIPSDK.dll和Newtonsoft.Json.dll这两个DLL
然后在全局变量中声明变量,在窗体加载事件中new个类,传入API_KEY和SECRET_KEY
string API_KEY = "cohIahxAt7HveHLYSHYK6G5N";
string SECRET_KEY = "e8SAsDIWSK9NPUKviYiPQNlfaVDXQSY5";
Ocr client;
private void Form1_Load(object sender, EventArgs e)
{
client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
2.传入图片地址,识别图片,返回识别结果
/// <summary>
/// 本地图片识别
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public string GeneralBasicDemo(string filename)
{
var image = File.ReadAllBytes(filename);
// 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
var result = client.GeneralBasic(image);
Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"language_type", "CHN_ENG"},
{"detect_direction", "true"},
{"detect_language", "true"},
{"probability", "true"}
};
// 带参数调用通用文字识别, 图片参数为本地图片
result = client.GeneralBasic(image, options);
return result.ToString();
}
/// <summary>
/// 联网图片识别
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string GeneralBasicUrlDemo(string url)
{
// 调用通用文字识别, 图片参数为远程url图片,可能会抛出网络等异常,请使用try/catch捕获
var result = client.GeneralBasicUrl(url);
Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"language_type", "CHN_ENG"},
{"detect_direction", "true"},
{"detect_language", "true"},
{"probability", "true"}
};
// 带参数调用通用文字识别, 图片参数为远程url图片
result = client.GeneralBasicUrl(url, options);
return result.ToString();
}
3.对识别的json进行解析,界面上显示
/// <summary>
/// 在界面上显示,解析图片
/// </summary>
/// <param name="returnstr"></param>
public void WriteTo(string returnstr)
{
try
{
ReturnJson rj = CYQ.Data.Tool.JsonHelper.ToEntity<ReturnJson>(returnstr);
string resultstr = "";
for (int i = 0; i < rj.words_result.Count; i++)
{
resultstr += rj.words_result[i].words + "\r\n";
}
richTextBox1.AppendText(resultstr + "\r\n");
}
catch (Exception ex)
{
MessageBox.Show("解析出错,出错原因:" + ex.Message);
}
}