引入依赖
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.15.8</version>
</dependency>
调用AipOcr
package com.study.baiduocr.util;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
public class ApiOcrUtil {
//设置APPID/AK/SK
private static String APP_ID = "";
private static String API_KEY ="";
private static String SECRET_KEY = "";
public static void main(String[] args) {
// 初始化一个AipOcr
AipOcr aipOcr = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
//设置本地图片地址
String path = "C:\\\\Users\\\\admin\\\\Desktop\\\\微信图片_20220311103037.png";
//通用文字识别
basicGeneral(aipOcr,path);
}
/*
* 通用文字识别
* */
public static void basicGeneral(AipOcr aipOcr,String path){
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("language_type", "CHN_ENG");//识别语言类型,默认为中英文混合
options.put("detect_direction", "true");//是否检查图片朝向,默认false不检查
options.put("detect_language", "true");//是否检查语言,默认false不检查
options.put("probability", "true");//是否返回识别结果中每一行的置信度
// 调用接口,返回JSON格式数据
JSONObject jsonObject = aipOcr.basicGeneral(path, options);
//获取JSON对象里提取图片文字信息数组
JSONArray jsonArray = jsonObject.getJSONArray("words_result");
//循环打印信息
for(int i = 0;i<jsonArray.length();i++){
System.out.println(jsonArray.getJSONObject(i).get("words"));
}
}
/*
* 身份证文字识别
* */
public static void idCord(AipOcr aipOcr,String path){
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("detect_direction", "true");//检查图片朝向。默认false不检测
options.put("detect_risk", "false");//是否开启身份证类型检测功能(类型为身份证复印件、临时身份证、身份证翻拍、修改过的身份证),默认false不开启
String idCardSide = "front";//身份证含照片一面
// String idCardSide = "back";//身份证含国徽一面
//本地图片识别,返回JSON对象
JSONObject jsonObject = aipOcr.idcard(path, idCardSide, options);
//获取到我们需要的信息
JSONObject result = jsonObject.getJSONObject("words_result");
//获取迭代器,
Iterator<String> iterator = result.keys();
while (iterator.hasNext()){
//获取键和值
String key = iterator.next();
String value = result.getJSONObject(key).getString("words");
//打印识别结果
System.out.println(key+" : "+value);
}
}
/*
* 车牌号识别
* */
public static void licencePlateNumber(AipOcr aipOcr,String path){
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("multi_detect", "false");//是否检测多张图片,默认false
//本地图片识别,返回JSON对象
JSONObject jsonObject = aipOcr.plateLicense(path, options);
//获取需要的信息
JSONObject result = jsonObject.getJSONObject("words_result");
System.out.println("车牌颜色:"+result.getString("color")+"\n"+"车牌号:"+result.getString("number"));
}
}
代码仓库地址
https://gitcode.net/m0_51527921/baiduocr.git