C#百度OCR-本地和网络图片识别文字

此种方法用的是百度接口,效果是可以,但是免费版一个月有使用上限,并且只能识别中英文,要想一直免费使用,突破使用次数,并且能识别韩日等其他语言的,可以参考我另一篇博客: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);
    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马儿不吃草

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值