總目錄地址: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格式
接口基礎封裝
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace BaiduAIAPI.Model 8 { 9 10 public class AccessTokenModel { 11 12 public bool IsSuccess { get; set; } 13 public SuccessAccessTokenModel SuccessModel { get; set; } 14 public ErrorAccessTokenModel ErrorModel { get; set; } 15 16 } 17 18 /// <summary> 19 /// 獲取accesstoken,正常 的 百度接口返回的json 實體模型 20 /// </summary> 21 public class SuccessAccessTokenModel 22 { 23 public string refresh_token { get; set; } 24 public int expires_in { get; set; } 25 public string scope { get; set; } 26 public string session_key { get; set; } 27 public string session_secret { get; set; } 28 29 public string access_token { get; set; } 30 } 31 32 /// <summary> 33 /// 獲取accesstoken,失敗的 百度接口返回的json 實體模型 34 /// </summary> 35 public class ErrorAccessTokenModel 36 { 37 public string error { get; set; } 38 public string error_description { get; set; } 39 40 } 41 }
1 using System; 2 using System.IO; 3 using System.Net; 4 using System.Text; 5 using System.Web; 6 using AOP.Common; 7 using AOP.Common.DataConversion; 8 using BaiduAIAPI.Model; 9 using BaiduAIAPI.Type; 10 11 namespace BaiduAIAPI.ORC_Characterbase64 12 { 13 14 /// <summary> 15 /// 文字識別--身份證識別 應用(只是獲取身份證圖片 信息,沒有和公安部聯網,無法確認真假,只是單純從圖片上識別文字) 16 /// </summary> 17 public class IDCardRecognition 18 { 19 // 身份證識別 20 21 /// <summary> 22 /// 身份證識別 23 /// </summary> 24 /// <param name="token">Accesstoken</param> 25 /// <param name="imagePath">圖片路徑</param> 26 /// <param name="recognitionString">識別結果</param> 27 /// <param name="errorMsg">錯誤信息</param> 28 /// <param name="id_card_side"> front:身份證正面;back:身份證背面</param> 29 /// <param name="detect_direction">是否檢測圖像朝向,默認不檢測,即:false。朝向是指輸入圖像是正常方向、逆時針旋轉90/180/270度。可選值包括:- true:檢測朝向;- false:不檢測朝向。</param> 30 /// <param name="detect_risk"> string 類型 是否開啟身份證風險類型(身份證復印件、臨時身份證、身份證翻拍、修改過的身份證)功能,默認不開啟,即:false。可選值:true-開啟;false-不開啟</param> 31 /// <returns>結果狀態</returns> 32 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") 33 { 34 bool resultState = true; 35 IDCardRecognitionModel tempModel = new IDCardRecognitionModel(); 36 37 try 38 { 39 #region 基礎校驗 40 string verificationMsg = ""; 41 errorMsg = ""; 42 bool isVerification = ImageVerification.VerificationImage(imagePath, out verificationMsg); 43 if (!isVerification) 44 { 45 46 errorMsg += verificationMsg; 47 tempModel.state = false; 48 tempModel.errorMsg = errorMsg; 49 return tempModel; 50 } 51 string strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg); // 圖片的base64編碼 52 Encoding encoding = Encoding.Default; 53 string urlEncodeImage = HttpUtility.UrlEncode(strbaser64); 54 55 byte[] tempBuffer = encoding.GetBytes(urlEncodeImage); 56 57 if (tempBuffer.Length > 1024 * 1024 * 4) 58 { 59 60 errorMsg += "圖片加密 后的大小超過4MB!"; 61 recognitionString = ""; 62 tempModel.state = false; 63 tempModel.errorMsg = errorMsg; 64 return tempModel; 65 66 } 67 #endregion 68 69 #region 請求接口 70 recognitionString = ""; 71 72 string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token; 73 String str = "id_card_side=" + id_card_side + "&detect_direction=" + detect_direction + "&detect_risk=" + detect_risk + "&image=" + HttpUtility.UrlEncode(strbaser64); 74 var tempResult = HttpRequestHelper.Post(host, str); 75 recognitionString = tempResult; 76 77 78 if (recognitionString.Contains("\"error_code\""))//說明異常 79 { 80 resultState = false; 81 tempModel.state = false; 82 tempModel.errorTypeModel = Json.ToObject<ErrorTypeModel>(tempResult); 83 tempModel.errorTypeModel.error_discription = ORC_CharacterRecognitionErrorType.GetErrorCodeToDescription(tempModel.errorTypeModel.error_code); 84 } 85 else 86 { 87 tempModel.state = true; 88 tempModel.successModel = Json.ToObject<IDCardRecognitionSuccessResultModel>(tempResult); 89 } 90 #endregion 91 92 return tempModel; 93 } 94 catch (Exception ex)//接口外部異常,如網絡異常 95 { 96 resultState = false; 97 errorMsg = ex.ToString(); 98 tempModel.state = false; 99 tempModel.errorMsg = ex.ToString(); 100 return tempModel; 101 102 } 103 } 104 105 } 106 107 }
winform 調用核心部分
1 /// <summary> 2 /// 識別操作 3 /// </summary> 4 /// <param name="filePath"></param> 5 /// <param name="id_card_side">身份證 正面還是背面</param> 6 /// <param name="detect_direction"></param> 7 /// <param name="detect_risk"></param> 8 public void Distinguish(string filePath, string id_card_side = "front", bool detect_direction = false, string detect_risk = "false") 9 { 10 DoTime();//主線程執行進度條,子線程進行數據請求操作 11 t1 = new Thread(new ThreadStart(() => 12 { 13 14 var temp = BaiduAIAPI.Access_Token.GetAccessToken(); 15 if (temp.IsSuccess) 16 { 17 string data = ""; 18 string error = ""; 19 var result = IDCardRecognition.GetIdcardRecognitionString(temp.SuccessModel.access_token, filePath, ref data, out error, id_card_side, detect_direction, detect_risk); 20 this.Invoke(new Action(() => 21 { 22 tb_showInfo.AppendText("\r\n -----------------------------------------------------------------"); 23 })); 24 25 if (result.state) 26 { 27 this.Invoke(new Action(() => 28 { 29 tb_showInfo.AppendText("\r\n ---------------------------識別成功-------------------------------"); 30 tb_showInfo.AppendText("\r\n" + result.successModel.ToJson() + "\r\n"); 31 })); 32 33 } 34 else 35 { 36 this.Invoke(new Action(() => 37 { 38 39 tb_showInfo.AppendText("\r\n-----------------------------識別失敗!--------------------------------"); 40 tb_showInfo.AppendText("\r\n" + result.successModel.ToJson() + result.errorMsg + "\r\n"); 41 })); 42 43 } 44 } 45 else 46 { 47 this.Invoke(new Action(() => 48 { 49 AttrMessage.ErrorMsg(temp.ErrorModel.error); 50 })); 51 52 } 53 54 this.Invoke(new Action(() => 55 { 56 progressBar_ToReadDistinguish.Value = 100; 57 timer1.Enabled = false; 58 progressBar_ToReadDistinguish.Value = 0; 59 })); 60 })); 61 62 t1.IsBackground = true; 63 t1.Start(); 64 65 }
效果如圖:圖中的身份證是我百度貼吧搜索的,不知道真偽。
PS:這個只是文字識別,並不是真正公安部聯網識別(身份有效性識別),要連接公安部識別需要 付費。
三、整合應用
筆者的應用是結合自己寫的插件化熱插拔模式寫的,把每個接口封裝成為一個插件,采用注入形式動態化結合
為了便於友好用戶體驗,在請求使用加入進度條,采用新的線程去進行接口請求,防止 界面卡住。
源碼地址:https://github.com/linbin524/AI_Project/tree/master
讀后感覺不錯,有收獲可以微信請作者喝杯咖啡,讀后有疑問請加微信,拉群研討,注明來意