总目录地址:AI 系列 总目录 

需要最新源码,或技术提问,请加QQ群:538327407

我的各种github 开源项目和代码:https://github.com/linbin524

简介

答应了园区大牛张善友 要写AI 的系列博客,所以开始了AI 系列之旅。

一、介绍

身份证识别 API 接口文档地址:http://ai.baidu.com/docs#/OCR-API/top

接口描述

用户向服务请求识别身份证,身份证识别包括正面和背面。

请求说明

请求示例

HTTP 方法:POST

请求URL: https://aip.baidubce.com/rest/2.0/ocr/v1/idcard

备注:你需要 成为百度开发者,获取API key 和Secret Key

Access_Token 的获取

百度Access_token 有效期有时间限制,大概是30天左右,所以建议封装成功能方法每次调用最新的。

  • access_token:要获取的Access Token;
  • expires_in:Access Token的有效期(秒为单位,一般为1个月);

二、技术实现

百度 文字识别 有提供SDK。如果有支持的语言,可以直接用sdk。笔者自己用的Http 请求封装

对于图片大小有要求的,图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式

接口基础封装

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace BaiduAIAPI.Model
{ public class AccessTokenModel { public bool IsSuccess { get; set; }
public SuccessAccessTokenModel SuccessModel { get; set; }
public ErrorAccessTokenModel ErrorModel { get; set; } } /// <summary>
/// 获取accesstoken,正常 的 百度接口返回的json 实体模型
/// </summary>
public class SuccessAccessTokenModel
{
public string refresh_token { get; set; }
public int expires_in { get; set; }
public string scope { get; set; }
public string session_key { get; set; }
public string session_secret { get; set; } public string access_token { get; set; }
} /// <summary>
/// 获取accesstoken,失败的 百度接口返回的json 实体模型
/// </summary>
public class ErrorAccessTokenModel
{
public string error { get; set; }
public string error_description { get; set; } }
}
 using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using AOP.Common;
using AOP.Common.DataConversion;
using BaiduAIAPI.Model;
using BaiduAIAPI.Type; namespace BaiduAIAPI.ORC_Characterbase64
{ /// <summary>
/// 文字识别--身份证识别 应用(只是获取身份证图片 信息,没有和公安部联网,无法确认真假,只是单纯从图片上识别文字)
/// </summary>
public class IDCardRecognition
{
// 身份证识别 /// <summary>
/// 身份证识别
/// </summary>
/// <param name="token">Accesstoken</param>
/// <param name="imagePath">图片路径</param>
/// <param name="recognitionString">识别结果</param>
/// <param name="errorMsg">错误信息</param>
/// <param name="id_card_side"> front:身份证正面;back:身份证背面</param>
/// <param name="detect_direction">是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:- true:检测朝向;- false:不检测朝向。</param>
/// <param name="detect_risk"> string 类型 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启</param>
/// <returns>结果状态</returns>
public static IDCardRecognitionModel GetIdcardRecognitionString(string token, string imagePath, ref string recognitionString, out string errorMsg, string id_card_side="front", bool detect_direction=false, string detect_risk="false")
{
bool resultState = true;
IDCardRecognitionModel tempModel = new IDCardRecognitionModel(); try
{
#region 基础校验
string verificationMsg = "";
errorMsg = "";
bool isVerification = ImageVerification.VerificationImage(imagePath, out verificationMsg);
if (!isVerification)
{ errorMsg += verificationMsg;
tempModel.state = false;
tempModel.errorMsg = errorMsg;
return tempModel;
}
string strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg); // 图片的base64编码
Encoding encoding = Encoding.Default;
string urlEncodeImage = HttpUtility.UrlEncode(strbaser64); byte[] tempBuffer = encoding.GetBytes(urlEncodeImage); if (tempBuffer.Length > * * )
{ errorMsg += "图片加密 后的大小超过4MB!";
recognitionString = "";
tempModel.state = false;
tempModel.errorMsg = errorMsg;
return tempModel; }
#endregion #region 请求接口
recognitionString = ""; string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token;
String str = "id_card_side=" + id_card_side + "&detect_direction=" + detect_direction + "&detect_risk=" + detect_risk + "&image=" + HttpUtility.UrlEncode(strbaser64);
var tempResult = HttpRequestHelper.Post(host, str);
recognitionString = tempResult; if (recognitionString.Contains("\"error_code\""))//说明异常
{
resultState = false;
tempModel.state = false;
tempModel.errorTypeModel = Json.ToObject<ErrorTypeModel>(tempResult);
tempModel.errorTypeModel.error_discription = ORC_CharacterRecognitionErrorType.GetErrorCodeToDescription(tempModel.errorTypeModel.error_code);
}
else
{
tempModel.state = true;
tempModel.successModel = Json.ToObject<IDCardRecognitionSuccessResultModel>(tempResult);
}
#endregion return tempModel;
}
catch (Exception ex)//接口外部异常,如网络异常
{
resultState = false;
errorMsg = ex.ToString();
tempModel.state = false;
tempModel.errorMsg = ex.ToString();
return tempModel; }
} } }

winform 调用核心部分

 /// <summary>
/// 识别操作
/// </summary>
/// <param name="filePath"></param>
/// <param name="id_card_side">身份证 正面还是背面</param>
/// <param name="detect_direction"></param>
/// <param name="detect_risk"></param>
public void Distinguish(string filePath, string id_card_side = "front", bool detect_direction = false, string detect_risk = "false")
{
DoTime();//主线程执行进度条,子线程进行数据请求操作
t1 = new Thread(new ThreadStart(() =>
{ var temp = BaiduAIAPI.Access_Token.GetAccessToken();
if (temp.IsSuccess)
{
string data = "";
string error = "";
var result = IDCardRecognition.GetIdcardRecognitionString(temp.SuccessModel.access_token, filePath, ref data, out error, id_card_side, detect_direction, detect_risk);
this.Invoke(new Action(() =>
{
tb_showInfo.AppendText("\r\n -----------------------------------------------------------------");
})); if (result.state)
{
this.Invoke(new Action(() =>
{
tb_showInfo.AppendText("\r\n ---------------------------识别成功-------------------------------");
tb_showInfo.AppendText("\r\n" + result.successModel.ToJson() + "\r\n");
})); }
else
{
this.Invoke(new Action(() =>
{ tb_showInfo.AppendText("\r\n-----------------------------识别失败!--------------------------------");
tb_showInfo.AppendText("\r\n" + result.successModel.ToJson() + result.errorMsg + "\r\n");
})); }
}
else
{
this.Invoke(new Action(() =>
{
AttrMessage.ErrorMsg(temp.ErrorModel.error);
})); } this.Invoke(new Action(() =>
{
progressBar_ToReadDistinguish.Value = ;
timer1.Enabled = false;
progressBar_ToReadDistinguish.Value = ;
}));
})); t1.IsBackground = true;
t1.Start(); }

效果如图:图中的身份证是我百度贴吧搜索的,不知道真伪。

PS:这个只是文字识别,并不是真正公安部联网识别(身份有效性识别),要连接公安部识别需要 付费。

三、整合应用

笔者的应用是结合自己写的插件化热插拔模式写的,把每个接口封装成为一个插件,采用注入形式动态化结合

为了便于友好用户体验,在请求使用加入进度条,采用新的线程去进行接口请求,防止 界面卡住。

源码地址:https://github.com/linbin524/AI_Project/tree/master

 

读后感觉不错,有收获可以微信请作者喝杯咖啡,读后有疑问请加微信,拉群研讨,注明来意

百度OCR文字识别-身份证识别的更多相关文章

  1. 百度OCR 文字识别 Android安全校验

    百度OCR接口使用总结: 之前总结一下关于百度OCR文字识别接口的使用步骤(Android版本 不带包名配置 安全性弱).这边博客主要介绍,百度OCR文字识别接口,官方推荐使用方式,授权文件(安全模式 ...

  2. 百度OCR文字识别-Android安全校验

    本文转载自好基友upuptop:https://blog.csdn.net/pyfysf/article/details/86438769 效果图: 如下为文章正文: 百度OCR接口使用总结:之前总结 ...

  3. 百度Ocr文字识别

    简述 最近开发一个项目需要用到Ocr文字识别技术来识别手写文字,在评估过程中体验了百度的文字识别和腾讯的文字识别.查找官方开发文档,发现它们都有印刷体和手写体两种符合项目需求的识别模式,但是腾讯的手写 ...

  4. 百度OCR文字识别API使用心得===com.baidu.ocr.sdk.exception.SDKError[283604]

    异常com.baidu.ocr.sdk.exception.SDKError[283604]App identifier unmatch.错误的packname或bundleId.logId::303 ...

  5. PHP:基于百度大脑api实现OCR文字识别

    有个项目要用到文字识别,网上找了很多资料,效果不是很好,偶然的机会,接触到百度大脑.百度大脑提供了很多解决方案,其中一个就是文字识别,百度提供了三种文字识别,分别是银行卡识别.身份证识别和通用文字识别 ...

  6. Java文字识别软件-调用百度ocr实现文字识别

    java_baidu_ocr Java调用百度OCR文字识别API实现图片文字识别软件 这是一款小巧方便,强大的文字识别软件,由Java编写,配上了窗口界面 调用了百度ocr文字识别API 识别精度高 ...

  7. 身份证识别OCR,开启视频模式扫一扫即可识别身份证信息

    文章摘要:身份证识别等证件识别OCR技术在各个行业得到广泛应用,例如:车险移动查勘会用到身份证识别.行驶证识别.车架号识别: 寿险移动展业会用到名片识别.银行卡识别:电信实名制代理网点采集身份证信息会 ...

  8. 【程序员的吃鸡大法】利用OCR文字识别+百度算法搜索,玩转冲顶大会、百万英雄、芝士超人等答题赢奖金游戏

    [先上一张效果图]: 一.原理: 其实原理很简单: 1.手机投屏到电脑: 2.截取投屏画面的题目部分,进行识别,得到题目和三个答案: 3.将答案按照一定的算法,进行搜索,得出推荐答案: 4.添加了一些 ...

  9. Ocr答题辅助神器 OcrAnswerer4.x,通过百度OCR识别手机文字,支持屏幕窗口截图和ADB安卓截图,支持四十个直播App,可保存题库

    http://www.cnblogs.com/Charltsing/p/OcrAnswerer.html 联系qq:564955427 最新版为v4.1版,开放一定概率的八窗口体验功能,请截图体验(多 ...

随机推荐

  1. C++流类库(11)

    C++的流类库由几个进行I/O操作的基础类和几个支持特定种类的源和目标的I/O操作的类组成. 流类库的基础类 ios类是isrream类和ostream类的虚基类,用来提供对流进行格式化I/O操作和错 ...

  2. 运用El表达式截取字符串/获取list的长度

    ${fn:substring(wjcd.lrsj, 0, 16)} 使用functions函数来获取list的长度 ${fn:length(list)} 引入 <%@ taglib prefix ...

  3. LeetCode 33. Search in Rotated Sorted Array(在旋转有序序列中搜索)

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  4. Redis主从环境配置

    1.Redis主从同步原理 redis主服务器会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,然后将数据文件同步给从服务器,从服务器加载记录文件,在内存库中更新新数据. 2.VMWar ...

  5. Python 数据分析Windows环境搭建

    1. 下载相应的Python软件并安装 python-3.6.0-amd64 2.  配置相应的环境变量path ;C:\Users\Administrator\AppData\Local\Progr ...

  6. Coursera上视频无法播放将怎么解决?

    相信很多朋友在播放Coursera中的视频都会遇到一个问题,视频全黑,点击播放,进度条转了一圈又消失不见. 这时候我们该找找是什么问题啦? 解决方法一: 如果你是FQ看的网课视频,那么你把VPN从au ...

  7. Codeforces Round #383 (Div. 2) B. Arpa’s obvious problem and Mehrdad’s terrible solution

    B. Arpa’s obvious problem and Mehrdad’s terrible solution time limit per test 1 second memory limit ...

  8. Python面向对象篇之元类,附Django Model核心原理

    关于元类,我写过一篇,如果你只是了解元类,看下面这一篇就足够了. Python面向对象之类的方法和属性 本篇是深度解剖,如果你觉得元类用不到,呵呵,那是因为你不了解Django. 在Python中有一 ...

  9. NTP时间服务器 搭建

    1.1 NTP简介 NTP(Network Time Protocol,网络时间协议)是用来使网络中的各个计算机时间同步的一种协议.它的用途是把计算机的时钟同步到世界协调时UTC,其精度在局域网内可达 ...

  10. awk练习题

    1. sed和awk有什么区别? (1)awk:按列(域)操作:sed:按行操作 (2)awk:文本处理语言,适合对文本进行抽取处理:sed:非交互式的编辑器,适合对文本进行编辑 2. awk要处理域 ...