注册百度账号及新增一个应用,获取百度API所需的AppID,API Key,Secret Key三个参数。
- 访问http://ai.baidu.com,使用百度账号登录后,出现如下界面
- 下载百度SDK
- 集成百度SDK
- 身份证中文字识别代码如下,简单几行代码就搞定,具体如下:
代码展示
package com.chinalife.maced_bdsdk.util;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import java.util.HashMap;
/**
* 参考:
* https://blog.csdn.net/jlq_diligence/article/details/87872177?ops_request_misc=&request_id=&biz_id=102&utm_term=%E8%BA%AB%E4%BB%BD%E8%AF%81%E8%AF%86%E5%88%ABJava&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-2-87872177.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187
*/
public class Sample {
// TODO APP_ID/AK/SK
public static final String APP_ID = "23552975";
public static final String API_KEY = "CS6wkhbrmjhiu9KUx2f6E51t";
public static final String SECRET_KEY = "useckvAI6kfMLhBDGOjwfAVrpgSNNI5o";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<>();
options.put("detect_direction", "true");
options.put("detect_risk", "false");
// 识别身份证正面(正面图片为本地图片,即:C:\Users\yy150\Pictures\正.jpg)
JSONObject frontres = client.idcard("C:\\Users\\yy150\\Pictures\\正.jpg", "front", options);
System.out.println(frontres.toString(2));
// 识别身份证反面(反面图片为本地图片,即:C:\Users\yy150\Pictures\反.jpg)
JSONObject backres = client.idcard("C:\\Users\\yy150\\Pictures\\反.jpg", "back", options);
System.out.println(backres.toString(2));
}
}
- 运行Sample中main()方法,运行后的结果,大致如下:
- 备注:识别出来的文字,为了安全起见,用***********代替。
// 正
{
"words_result": {
"姓名": {
"words": "百度熊",
"location": {
"top": 34,
"left": 82,
"width": 58,
"height": 22
}
},
"民族": {
"words": "汉",
"location": {
"top": 74,
"left": 171,
"width": 17,
"height": 19
}
},
"住址": {
"words": "北京市海淀区上地十号七栋2单元110室",
"location": {
"top": 149,
"left": 76,
"width": 203,
"height": 41
}
},
"公民身份号码": {
"words": "532101198906010015",
"location": {
"top": 240,
"left": 137,
"width": 256,
"height": 20
}
},
"出生": {
"words": "19890601",
"location": {
"top": 110,
"left": 78,
"width": 152,
"height": 17
}
},
"性别": {
"words": "男",
"location": {
"top": 74,
"left": 77,
"width": 18,
"height": 19
}
}
},
"log_id": 1350711547869003776,
"words_result_num": 6,
"idcard_number_type": 1,
"image_status": "normal",
"direction": 0
}
// 反
{
"words_result": {
"失效日期": {
"words": "***********",
"location": {
"height": 22,
"width": 90,
"left": 308,
"top": 263
}
},
"签发机关": {
"words": "***********",
"location": {
"height": 30,
"width": 265,
"left": 201,
"top": 215
}
},
"签发日期": {
"words": "***********",
"location": {
"height": 22,
"width": 95,
"left": 198,
"top": 258
}
}
},
"direction": 0,
"words_result_num": 3,
"image_status": "normal",
"log_id": 3369545259709262582
}