zoukankan      html  css  js  c++  java
  • 单一功能学习——百度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 }
  • 相关阅读:
    使用kubeadm部署K8S v1.17.0集群
    06Shell并发控制
    05Shell循环语句
    04Shell流程控制
    03Shell条件测试
    02Shell变量
    01Shell入门02-echo和printf
    01Shell入门01-bash Shell特性
    局域网部署ntp时间服务器
    聊聊、Mybatis集成Spring XML方式
  • 原文地址:https://www.cnblogs.com/qq765065332/p/8716793.html
Copyright © 2011-2022 走看看