调用百度Api读取图片文字 C#
1.注册百度Api
2.引用 c# SDK
安装文字识别 C# SDK
C# SDK 现已开源! https://github.com/Baidu-AIP/dotnet-sdk
** 支持平台:.Net Framework 3.5 4.0 4.5, .Net Core 2.0 **
方法一:使用Nuget管理依赖 (推荐)
在NuGet中搜索 Baidu.AI,安装最新版即可。
packet地址 https://www.nuget.org/packages/Baidu.AI/
方法二:下载安装
文字识别 C# SDK目录结构
Baidu.Aip
├── net35
│ ├── AipSdk.dll // 百度AI服务 windows 动态库
│ ├── AipSdk.xml // 注释文件
│ └── Newtonsoft.Json.dll // 第三方依赖
├── net40
├── net45
└── netstandard2.0
├── AipSdk.deps.json
└── AipSdk.dll
在官方网站下载C# SDK压缩工具包;解压后,将 AipSdk.dll 和 Newtonsoft.Json.dll 中添加为引用。
3.demo源码:
using Newtonsoft.Json.Linq;
using System.IO;
namespace HelperBll
{
public class ImgApiBll
{
//基础参数:从配置文件取过来
private readonly string _api_key;//百度api键值
private readonly string _secret_key;//百度api秘钥
private readonly int _timeOut;//超时设置
public ImgApiBll(string api_key, string secret_key, int timeOut )
{
_api_key = api_key;
_secret_key = secret_key;
_timeOut = timeOut;
}
/// <summary>
/// 文字-json格式
/// </summary>
/// <param name="imgPath">图片地址</param>
/// <returns></returns>
public string ReadImgTxt(string imgPath)
{
var client = new Baidu.Aip.Ocr.Ocr(_api_key, _secret_key)
{
Timeout = _timeOut //超时时间
};
//本地图片
byte[] imgStream = File.ReadAllBytes(imgPath); //图片二进制
JObject jsonResult = client.GeneralBasic(imgStream);
//网络图片
//JObject jsonResult = client.GeneralBasicUrl(imgUrl);
//JObject jsonResult = client.Accurate(imgStream); //本地图片:相对于通用文字识别该产品精度更高,但是识别耗时会稍长。
//JObject jsonResult = client.General(imgStream); //本地图片:通用文字识别(含位置信息版)
//JObject jsonResult = client.GeneralUrl(imgUrl); //网络图片:通用文字识别(含位置信息版)
//JObject jsonResult = client.GeneralEnhanced(imgStream); //本地图片:调用通用文字识别(含生僻字版)
//JObject jsonResult = client.GeneralEnhancedUrl(imgUrl); //网络图片:调用通用文字识别(含生僻字版)
//JObject jsonResult = client.WebImage(imgStream); //本地图片:用户向服务请求识别一些背景复杂,特殊字体的文字。
//JObject jsonResult = client.WebImageUrl(imgUrl); //网络图片:用户向服务请求识别一些背景复杂,特殊字体的文字。
return jsonResult.ToString();
}
}
}
4. 程序效果:
图片示例:


读出文字结果:
{{
"log_id": 2872598628702849350,
"words_result_num": 18,
"words_result": [
{
"words": "接口名称"
},
{
"words": "接口能力简要描述"
},
{
"words": "通用文字识别"
},
{
"words": "识别图片中的文字信息"
},
{
"words": "通用文字识别(高精度版)"
},
{
"words": "更高精度地识别图片中的文字信息"
},
{
"words": "通用文字识别(含位置信息版)识别图片中的文字信息(包含文字区域的坐标信息)"
},
{
"words": "通用文字识别(高精度含位置更高精度地识别图片中的文字信息(包含文字区域的坐标信息)"
},
{
"words": "通用文字识别(含生僻字版)识别图片中的文字信息(包含对常见字和生僻字的识别)"
},
{
"words": "网络片文字识别"
},
{
"words": "识别一些网络上背景复杂,特殊字体的文字"
},
{
"words": "身份证识别"
},
{
"words": "识别身份证正反面的文字信息"
},
{
"words": "银行卡识另"
},
{
"words": "识别银行卡的卡号并返回发卡行和卡片性质信息"
},
{
"words": "识别机动车驾驶证所有关键字段"
},
{
"words": "行驶证识别"
},
{
"words": "识别机动车行驶证所有关键字段"
}
]
}}
5.总结:
文字截图,基本是可以完整读出来的。
参考:https://www.cnblogs.com/xiongze520/p/11283484.html

浙公网安备 33010602011771号