單一功能學習——百度AI之身份證識別


以下內容基本是從官方接口文檔復制過來的,附帶自己封裝的代碼

 

時間:2018年4月4日

 

一、導入工具包

  使用maven依賴:

1 <dependency>
2     <groupId>com.baidu.aip</groupId>
3     <artifactId>java-sdk</artifactId>
4     <version>${version}</version>
5 </dependency>

  自己下載:

    下載Java SDK壓縮工具包:https://ai.baidu.com/sdk#ocr  

    在Eclipse右鍵“工程 -> Properties -> Java Build Path -> Add JARs”

    添加SDK工具包  aip-java-sdk-版本.jar 和第三方依賴工具包json-20160810.jar log4j-1.2.17.jar

 

二、新建AipOcr

   官方示例:

 1 public class Sample {
 2     //設置APPID/AK/SK
 3     public static final String APP_ID = "你的 App ID";
 4     public static final String API_KEY = "你的 Api Key";
 5     public static final String SECRET_KEY = "你的 Secret Key";
 6 
 7     public static void main(String[] args) {
 8         // 初始化一個AipOcr
 9         AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
10 
11         // 可選:設置網絡連接參數
12         client.setConnectionTimeoutInMillis(2000);
13         client.setSocketTimeoutInMillis(60000);
14 
15         // 可選:設置代理服務器地址, http和socket二選一,或者均不設置
16         client.setHttpProxy("proxy_host", proxy_port);  // 設置http代理
17         client.setSocketProxy("proxy_host", proxy_port);  // 設置socket代理
18 
19         // 可選:設置log4j日志輸出格式,若不設置,則使用默認配置
20         // 也可以直接通過jvm啟動參數設置此環境變量
21         System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");
22 
23         // 調用接口
24         String path = "test.jpg";
25         JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
26         System.out.println(res.toString(2));
27         
28     }
29 }

 

   其中示例的log4j.properties文件內容如下:

 1 #可以設置級別:debug>info>error
 2 #debug:顯示debug、info、error
 3 #info:顯示info、error
 4 #error:只error
 5 log4j.rootLogger=debug,appender1
 6 #log4j.rootLogger=info,appender1
 7 #log4j.rootLogger=error,appender1
 8 
 9 #輸出到控制台
10 log4j.appender.appender1=org.apache.log4j.ConsoleAppender
11 #樣式為TTCCLayout
12 log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
13 
14 #自定義樣式
15 # %r 時間 0
16 # %t 方法名 main
17 # %p 優先級 DEBUG/INFO/ERROR
18 # %c 所屬類的全名(包括包名)
19 # %l 發生的位置,在某個類的某行
20 # %m 輸出代碼中指定的訊息,如log(message)中的message
21 # %n 輸出一個換行
22 
23 log4j.appender.appender1.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss:SSS}][%t][%p] -%l %m%n

 

 

 三、配置AipOcr

  如果用戶需要配置AipOcr的一些細節參數,可以在構造AipOcr之后調用接口設置參數,目前只支持以下參數:

接口 說明
setConnectionTimeoutInMillis 建立連接的超時時間(單位:毫秒)
setSocketTimeoutInMillis 通過打開的連接傳輸數據的超時時間(單位:毫秒)
setHttpProxy 設置http代理服務器
setSocketProxy 設置socket代理服務器 (http和socket類型代理服務器只能二選一)

 

 四、接口調用

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

 1 public void sample(AipOcr client) {
 2     // 傳入可選參數調用接口
 3     HashMap<String, String> options = new HashMap<String, String>();
 4     options.put("detect_direction", "true");
 5     options.put("detect_risk", "false");
 6     
 7     String idCardSide = "back";
 8     
 9     // 參數為本地圖片路徑
10     String image = "test.jpg";
11     JSONObject res = client.idcard(image, idCardSide, options);
12     System.out.println(res.toString(2));
13 
14     // 參數為本地圖片二進制數組
15     byte[] file = readImageFile(image);
16     res = client.idcard(file, idCardSide, options);
17     System.out.println(res.toString(2));
18 
19 }

  請求參數詳情

參數名稱 是否必選 類型 可選值范圍 默認值 說明
image mixed     本地圖片路徑或者圖片二進制數據
id_card_side String front - 身份證含照片的一面
back - 身份證帶國徽的一面
  front:身份證含照片的一面;back:身份證帶國徽的一面
detect_direction String true
false
false 是否檢測圖像朝向,默認不檢測,即:false。朝向是指輸入圖像是正常方向、逆時針旋轉90/180/270度。可選值包括:
- true:檢測朝向;
- false:不檢測朝向。
detect_risk String true - 開啟
false - 不開啟
  是否開啟身份證風險類型(身份證復印件、臨時身份證、身份證翻拍、修改過的身份證)功能,默認不開啟,即:false。可選值:true-開啟;false-不開啟

 

  返回數據參數詳情

字段 是否必選 類型 說明
direction number 圖像方向,當detect_direction=true時存在。
- -1:未定義,
- 0:正向,
- 1: 逆時針90度,
- 2:逆時針180度,
- 3:逆時針270度
image_status string normal-識別正常
reversed_side-未擺正身份證
non_idcard-上傳的圖片中不包含身份證
blurred-身份證模糊
over_exposure-身份證關鍵字段反光或過曝
unknown-未知狀態
risk_type string 輸入參數 detect_risk = true 時,則返回該字段識別身份證類型: normal-正常身份證;copy-復印件;temporary-臨時身份證;screen-翻拍;unknow-其他未知情況
edit_tool string 如果參數 detect_risk = true 時,則返回此字段。如果檢測身份證被編輯過,該字段指定編輯軟件名稱,如:Adobe Photoshop CC 2014 (Macintosh),如果沒有被編輯過則返回值無此參數
log_id number 唯一的log id,用於問題定位
words_result array(object) 定位和識別結果數組
words_result_num number 識別結果數,表示words_result的元素個數
+location array(object) 位置數組(坐標0點為左上角)
++left number 表示定位位置的長方形左上頂點的水平坐標
++top number 表示定位位置的長方形左上頂點的垂直坐標
++width number 表示定位位置的長方形的寬度
++height number 表示定位位置的長方形的高度
+words string 識別結果字符串

   返回示例

 1 {
 2     "log_id": 2648325511,
 3     "direction": 0,
 4     "image_status": "normal",
 5     "idcard_type": "normal",
 6     "edit_tool": "Adobe Photoshop CS3 Windows",
 7     "words_result": {
 8         "住址": {
 9             "location": {
10                 "left": 267,
11                 "top": 453,
12                 "width": 459,
13                 "height": 99
14             },
15             "words": "南京市江寧區弘景大道3889號"
16         },
17         "公民身份號碼": {
18             "location": {
19                 "left": 443,
20                 "top": 681,
21                 "width": 589,
22                 "height": 45
23             },
24             "words": "330881199904173914"
25         },
26         "出生": {
27             "location": {
28                 "left": 270,
29                 "top": 355,
30                 "width": 357,
31                 "height": 45
32             },
33             "words": "19990417"
34         },
35         "姓名": {
36             "location": {
37                 "left": 267,
38                 "top": 176,
39                 "width": 152,
40                 "height": 50
41             },
42             "words": "伍雲龍"
43         },
44         "性別": {
45             "location": {
46                 "left": 269,
47                 "top": 262,
48                 "width": 33,
49                 "height": 52
50             },
51             "words": "男"
52         },
53         "民族": {
54             "location": {
55                 "left": 492,
56                 "top": 279,
57                 "width": 30,
58                 "height": 37
59             },
60             "words": "漢"
61         }
62     },
63     "words_result_num": 6
64 }

 

 

 五、我封裝的類

 1 package com.xxxxx.util;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.InputStream;
 6 import java.util.HashMap;
 7 import org.apache.commons.lang3.StringUtils;
 8 import org.json.JSONObject;
 9 import com.baidu.aip.ocr.AipOcr;
10 
11 public class AipOcrJDKFactory {
12 
13     // 設置APPID/AK/SK
14     public static final String APP_ID = "xxxxx";
15     public static final String API_KEY = "xxxxxxxxxxxxxxxxxx";
16     public static final String SECRET_KEY = "xxxxxxxxxxxxxxxxxxx";
17 
18     public static final AipOcrJDKFactory INST = new AipOcrJDKFactory();
19     public static AipOcr client;
20 
21     private AipOcrJDKFactory() {
22         // 初始化一個AipOcr
23         client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
24         // 可選:設置網絡連接參數
25         client.setConnectionTimeoutInMillis(2000);
26         client.setSocketTimeoutInMillis(60000);
27     }
28 
29     /**
30      * 身份證識別
31      * 
32      * @param isFront
33      *            :true識別身份證正面;false識別身份證背面;
34      * @param isDirection
35      *            :是否開啟檢測旋轉角度並矯正識別,建議為true
36      * @param isRisk
37      *            :是否開啟身份證風險類型(身份證復印件、臨時身份證、身份證翻拍、修改過的身份證)功能,默認不開啟
38      * @param imagePath
39      *            :圖片本地路徑
40      * @return
41      */
42     public JSONObject idcardRecognition(boolean isFront, boolean isDirection, boolean isRisk, String imagePath) {
43         if (StringUtils.isEmpty(imagePath)) {
44             return null;
45         }
46         File file = new File(imagePath);
47         if (!file.exists() || !file.isFile()) {
48             return null;
49         }
50         // 傳入可選參數調用接口,默認為false
51         HashMap<String, String> options = new HashMap<String, String>();
52         options.put("detect_direction", isDirection ? "true" : "false");
53         options.put("detect_risk", isRisk ? "true" : "false");
54         // 識別身份證正面idCardSide=front;識別身份證背面idCardSide=back;
55         String idCardSide = isFront ? "front" : "back";
56         // 參數為本地圖片路徑
57         JSONObject res = client.idcard(imagePath, idCardSide, options);
58         System.out.println("(boolean isFront, String imagePath) res:" + res.toString(2));
59         return res;
60 
61     }
62 
63     /**
64      * 身份證識別
65      * 
66      * @param isFront
67      *            :true識別身份證正面;false識別身份證背面;
68      * @param fileBytes
69      *            :圖片byte[]
70      * @return
71      */
72     public JSONObject idcardRecognition(boolean isFront,  byte[] fileBytes) {
73         if (fileBytes == null) {
74             return null;
75         }
76         // 傳入可選參數調用接口
77         HashMap<String, String> options = new HashMap<String, String>();
78         options.put("detect_direction", "true");
79         options.put("detect_risk", "false");
80         // 識別身份證正面idCardSide=front;識別身份證背面idCardSide=back;
81         String idCardSide = isFront ? "front" : "back";
82         // 參數為本地圖片二進制數組
83         JSONObject res = client.idcard(fileBytes, idCardSide, options);
84         System.out.println("client.idcard(fileBytes, idCardSide, options) res:" + res.toString(2));
85         return res;
86     }
87 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM