日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

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

發(fā)布時間:2023/12/24 综合教程 28 生活家
生活随笔 收集整理的這篇文章主要介紹了 百度OCR文字识别-身份证识别 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

簡介

一、介紹

身份證識別 API 接口文檔地址:http://ai.baidu.com/docs

接口描述

用戶向服務請求識別身份證,身份證識別包括正面和背面。

請求說明

請求示例

HTTP 方法:POST

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

備注:你需要 成為百度開發(fā)者,獲取API key 和Secret Key

Access_Token 的獲取

百度Access_token 有效期有時間限制,大概是30天左右,所以建議封裝成功能方法每次調(diào)用最新的。

access_token:要獲取的Access Token;
expires_in:Access Token的有效期(秒為單位,一般為1個月);

二、技術實現(xiàn)

百度 文字識別 有提供SDK。如果有支持的語言,可以直接用sdk。筆者自己用的Http 請求封裝

對于圖片大小有要求的,圖像數(shù)據(jù),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>
    /// 文字識別--身份證識別 應用(只是獲取身份證圖片 信息,沒有和公安部聯(lián)網(wǎng),無法確認真假,只是單純從圖片上識別文字)
    /// </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>結果狀態(tài)</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)//接口外部異常,如網(wǎng)絡異常
            {
                resultState = false;
                errorMsg = ex.ToString();
                tempModel.state = false;
                tempModel.errorMsg = ex.ToString();
                return tempModel;
               
            }
        }

    }

}

winform 調(diào)用核心部分

/// <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();//主線程執(zhí)行進度條,子線程進行數(shù)據(jù)請求操作
            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("
 -----------------------------------------------------------------");
                    }));

                    if (result.state)
                    {
                        this.Invoke(new Action(() =>
                        {
                            tb_showInfo.AppendText("
 ---------------------------識別成功-------------------------------");
                            tb_showInfo.AppendText("
" + result.successModel.ToJson() + "
");
                        }));

                    }
                    else
                    {
                        this.Invoke(new Action(() =>
                        {

                            tb_showInfo.AppendText("
-----------------------------識別失敗!--------------------------------");
                            tb_showInfo.AppendText("
" + result.successModel.ToJson() + result.errorMsg + "
");
                        }));

                    }
                }
                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();

        }

效果如圖:圖中的身份證是我百度貼吧搜索的,不知道真?zhèn)巍?/p>

PS:這個只是文字識別,并不是真正公安部聯(lián)網(wǎng)識別(身份有效性識別),要連接公安部識別需要 付費。

三、整合應用

筆者的應用是結合自己寫的插件化熱插拔模式寫的,把每個接口封裝成為一個插件,采用注入形式動態(tài)化結合

為了便于友好用戶體驗,在請求使用加入進度條,采用新的線程去進行接口請求,防止 界面卡住。

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

總結

以上是生活随笔為你收集整理的百度OCR文字识别-身份证识别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。