百度OCR文字识别-身份证识别

简介 

 答应了园区大牛张善友 要写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 > 1024 * 1024 * 4)

                {


                    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 = 100;

                    timer1.Enabled = false;

                    progressBar_ToReadDistinguish.Value = 0;

                }));

            }));


            t1.IsBackground = true;

           t1.Start();


        }

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

 

 

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

 

三、整合应用

 

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

 

 

 

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


相关文章: 

  • Build 2017  | 一文看懂微软 Build 2017 大会:让 AI 走向边缘

  • 认识微软Visual Studio Tools for AI

  • VS Tools for AI全攻略

  • VS Tools for AI全攻略(2)低配置虚拟机也能玩转深度学习,无需NC/NV系列

  • 基于Emgu CV+百度人脸识别,实现视频动态 人脸抓取与识别

原文:http://www.cnblogs.com/linbin524/p/BaiduOCR_IDCard.html


.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/322650.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring Boot Elasticsearch 入门

转载自 芋道 Spring Boot Elasticsearch 入门 1. 概述 如果胖友之前有用过 Elasticsearch 的话&#xff0c;可能有过被使用的 Elasticsearch 客户端版本搞死搞活。如果有&#xff0c;那么一起握个抓。所以&#xff0c;我们在文章的开始&#xff0c;先一起理一理这块。 Elas…

内存不足The following exception is caused by a lack of memory or swap, or not having swap

在linux执行以下三个命令即可 /bin/dd if/dev/zero of/var/swap.1 bs1M count1024 /sbin/mkswap /var/swap.1 /sbin/swapon /var/swap.1

P2513-[HAOI2009]逆序对数列【dp,前缀和】

正题 题目链接:https://www.luogu.org/problemnew/show/P2513 题目大意 求长度为nnn逆序对为kkk个的序列总数。 解题思路 设fi,jf_{i,j}fi,j​表示1∼i1\sim i1∼i的排列逆序对个数为jjj 然后显然:fi,j∑k1i−1fi−1,j−kf_{i,j}\sum_{k1}^{i-1}f_{i-1,j-k}fi,j​k1∑i−1​…

在.NET Core类库中使用EF Core迁移数据库到SQL Server

前言 如果大家刚使用EntityFramework Core作为ORM框架的话&#xff0c;想必都会遇到数据库迁移的一些问题。 起初我是在ASP.NET Core的Web项目中进行的&#xff0c;但后来发现放在此处并不是很合理&#xff0c;一些关于数据库的迁移&#xff0c;比如新增表&#xff0c;字段&…

Spring Boot MongoDB 入门

转载自 芋道 Spring Boot MongoDB 入门 1. 概述 可能有一些胖友对 MongoDB 不是很了解&#xff0c;这里我们引用一段介绍&#xff1a; FROM 《分布式文档存储数据库 MongoDB》 MongoDB 是一个介于关系数据库和非关系数据库之间的产品&#xff0c;是非关系数据库当中功能最…

composer配置阿里云镜像

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

CF735D-Taxes【数学,数论】

正题 luogu题目链接:https://www.luogu.org/problemnew/show/CF735D 题目大意 将一个数分解成若干个数使得这若干个数的最大因子最小。 解题思路 如果是质数就是1。如果是偶数根据哥德巴赫猜想就是2。或者把一个奇数减去2后是个质数也是2。否则就是3。 codecodecode #inclu…

Spring框架-事务管理注意事项

转载自 Spring框架-事务管理注意事项 常见事务问题 事务不起作用 可能是配置不起效&#xff0c;如扫描问题 事务自动提交了&#xff08;批量操作中&#xff09; 可能是在没事务的情况下&#xff0c;利用了数据库的隐式提交 事务配置说明 通常情况下我们的Spring Component扫…

P2568-GCD【欧拉函数,欧拉筛】

正题 题目链接:https://www.luogu.org/problemnew/show/P2568 题目大意 求有多少个数对满足gcd(x,y)pri(x,y≤n)gcd(x,y)pri(x,y\leq n)gcd(x,y)pri(x,y≤n) 解题思路 首先对于 gcd(x,y)pgcd(x,y)pgcd(x,y)p >gcd(x/p,y/p)1>gcd(x/p,y/p)1>gcd(x/p,y/p)1 那么对数就…

laravel允许所有网站进行跨域操作

共三步&#xff1a; 1、新建中间件&#xff1a; php artisan make:middleware EnableCrossRequestMiddleware2、EnableCrossRequestMiddleware.php中重写中间件里面的内容&#xff1a; <?php namespace App\Http\Middleware; use Closure; class EnableCrossRequestMidd…

Ocelot统一权限验证

Ocelot作为网关&#xff0c;可以用来作统一验证&#xff0c;接上一篇博客Ocelot网关&#xff0c;我们继续 前一篇&#xff0c;我们创建了OcelotGateway网关项目&#xff0c;DemoAAPI项目&#xff0c;DemoBAPI项目&#xff0c;为了验证用户并分发Token&#xff0c;现在还需要添…

P1081-开车旅行【倍增,链表,dp】

正题 题目大意:https://www.luogu.org/problemnew/show/P1081 题目大意 有若干个城市有不同的海拔hhh&#xff0c;两个城市之间的距离定义为∣hx−hy∣|h_x-h_y|∣hx​−hy​∣ 小A每次走次近的&#xff0c;小B每次走最近的。它们轮流开车。且只会往编号更大的城市开。 问一:…

Spring Boot之程序性能监控

转载自 Spring Boot之程序性能监控 Spring Boot特别适合团队构建各种可快速迭代的微服务&#xff0c;同时为了减少程序本身监控系统的开发量&#xff0c;Spring Boot提供了actuator模块&#xff0c;可以很方便的对你的Spring Boot程序做监控。 1. actuator接口说明 Spring B…

laravel部署在linux出现404 not found

laravel项目放在本地服务器后&#xff0c;访问是成功的 http://localhost/blogkjh/public/article 但是在linux服务器上访问显示404 not found 但是我在服务器上使用 php artisan serve --host 0.0.0.0 命令 却可以访问 甚至连swagger都可以访问 关于这个我最近就特别疑…

Visual Studio 2017 15.6版本预览,增加新功能

上周Visual Studio 2017 15.5 版本已正式发布&#xff0c;同时发布的还有 Visual Studio for Mac 7.3 。 Visual Studio 2017 15.6 版本预览&#xff0c;这个最新的预览包含新功能&#xff0c;生产力改进和其他增强功能&#xff0c;以解决客户的反馈意见。 本发行版中的更新摘要…

POJ1275-Cashier Employment【差分约束系统】

正题 题目链接:http://poj.org/problem?id1275 题目大意 1∼241\sim 241∼24小时中第iii个小时需要rir_iri​个出纳员 有nnn个人应聘&#xff0c;第iii从xix_ixi​开始工作&#xff0c;一直工作8个小时。 求至少要招募多少人应聘。 解题思路 numinum_inumi​表示第iii个小时有…

使用 mono 编译 .NET Standard 应用

微软发布 .NET Standard 2.0 已经有一段时间了&#xff0c; 根据 .NET Standard 2.0 支持版本的文档&#xff0c; Mono 5.4 是支持 .NET Standard 2.0 的&#xff0c; 对于 .NET Standard 2.0 应用的开发的介绍&#xff0c; 几乎全部都是在 Windows 系统下使用 Visual Studio 2…

nginx操作命令

启动 nginx 停止 nginx -s stop 查看占用端口号 ps -ef | grep nginx 重启&#xff1a; nginx -s reload nginx配置目录&#xff1a; /usr/local/nginx/conf/nginx.conf

Spring Boot 热部署入门

转载自 Spring Boot 热部署入门 1. 概述 在日常开发中&#xff0c;我们需要经常修改 Java 代码&#xff0c;手动重启项目&#xff0c;查看修改后的效果。如果在项目小时&#xff0c;重启速度比较快&#xff0c;等待的时间是较短的。但是随着项目逐渐变大&#xff0c;重启的速…

hdu3666-THE MATRIX PROBLEM【差分约束,自然对数】

正题 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid3666 题目大意 一个n∗mn*mn∗m的矩阵CCC求有没有一个长度为nnn的aaa序列和一个长度为mmm的bbb序列使得 L≤Ci,j∗ai/bi≤RL\leq C_{i,j}*a_i/b_i\leq RL≤Ci,j​∗ai​/bi​≤R 解题思路 首先我们将乘除转换为自然…