자바 바 이 두 클 라 우 드 OCR 문자 인식 고밀도 OCR 식별 신분증 정보 실현
1.통용 OCR 문자 인식
이런 OCR 은 그림 에 있 는 문자 만 식별 할 수 있 고 줄 에 따라 결 과 를 되 돌려 주 며 정밀도 가 낮다.
우선 의존 팩 도입:
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.6.0</version>
</dependency>
OCR 도구 클래스 통과 하기:
package util;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import java.util.HashMap;
public class OcrApi {
private static final String APP_ID = " App ID";
private static final String API_KEY = "Xb12m5t4jS2n7";
private static final String SECRET_KEY = "9XVx9GPcSbSUTZ";
private static AipOcr getAipClient() {
return getAipClient(API_KEY, SECRET_KEY);
}
public static AipOcr getAipClient(String apiKey, String secretKey) {
AipOcr client = new AipOcr(APP_ID, apiKey, secretKey);
// :
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
return client;
}
public static String result(AipOcr client) {
//
HashMap<String, String> options = new HashMap<>();
options.put("language_type", "CHN_ENG");
options.put("detect_direction", "true");
options.put("detect_language", "true");
options.put("probability", "true");
JSONObject res = client.basicGeneralUrl(
"https://lichunyu1234.oss-cn-shanghai.aliyuncs.com/1.png", options);
return res.toString(2);
}
public static void main(String[] args) {
System.out.println(result(getAipClient()));
}
}
결 과 는 다음 과 같다.두 줄 의 정보(words 즉 식 별 된 정보)를 식별한다.2.고밀도 OCR 식별 신분증 정보
이런 것 은 비교적 높 은 정밀도 와 분류 에 따라 데 이 터 를 되 돌려 주 는 것 이 더욱 우호 적 이 고 사용 가능 하 다.
2.1 인터페이스 설명 과 요청 매개 변 수 는 주소 공식 캡 처 입 니 다.다음 과 같 습 니 다.
2.2 OCR 신분증 식별 도구 류
package util;
import com.alibaba.druid.util.Base64;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
public class OcrUtil {
// Access_Token
private static final String ACCESS_TOKEN_HOST = "https://aip.baidubce.com/oauth/2.0/token?";
// URL
private static final String OCR_HOST = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?";
// apiKey,secretKey
private static final String API_KEY ="Xb12m5t4jS";
private static final String SECRET_KEY = "9XVx9GPcSbSUT";
// OCR access_token
public static String getAccessToken() {
return getAccessToken(API_KEY, SECRET_KEY);
}
/**
* OCR access_token
* @param apiKey
* @param secretKey
* @return
*/
public static String getAccessToken(String apiKey, String secretKey) {
String accessTokenURL = ACCESS_TOKEN_HOST
// 1. grant_type
+ "grant_type=client_credentials"
// 2. API Key
+ "&client_id=" + apiKey
// 3. Secret Key
+ "&client_secret=" + secretKey;
try {
URL url = new URL(accessTokenURL);
// URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//
Map<String, List<String>> map = connection.getHeaderFields();
//
for (String key : map.keySet()) {
System.out.println(key + "---->" + map.get(key));
}
// BufferedReader URL
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
result.append(inputLine);
}
JSONObject jsonObject = JSONObject.parseObject(result.toString());
return jsonObject.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
System.err.print(" access_token ");
}
return null;
}
/**
*
* @param imageUrl
* @param idCardSide
* @return
*/
public static String getStringIdentityCard(File imageUrl, String idCardSide) {
// OCR http URL+ token
String OCRUrl = OCR_HOST+"access_token="+getAccessToken();
System.out.println(OCRUrl);
System.out.println("***************************************************");
System.out.println(getAccessToken());
// base64
String image = encodeImageToBase64(imageUrl);
//
String requestParam = "detect_direction=true&id_card_side="+idCardSide+"&image="+image;
try {
// OCR
URL url = new URL(OCRUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// POST
connection.setRequestMethod("POST");
//
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("apiKey", API_KEY);
connection.setDoOutput(true);
connection.getOutputStream().write(requestParam.getBytes(StandardCharsets.UTF_8));
connection.connect();
// BufferedReader URL
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
result.append(inputLine);
}
bufferedReader.close();
return result.toString();
} catch (Exception e) {
e.printStackTrace();
System.err.println(" OCR ");
return null;
}
}
/**
* url Base64
* @param imageUrl
* @return
*/
public static String encodeImageToBase64(File imageUrl) {
// , Base64
byte[] data = null;
try {
InputStream inputStream = new FileInputStream(imageUrl);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
// Base64
return URLEncoder.encode(Base64.byteArrayToBase64(data), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* OCR
* @param
* @return
*/
public static Map<String, String> getIdCardInfo(MultipartFile image, int idCardSide) {
String value = getStringIdentityCard(image, idCardSide);
String side;
if (idCardSide == 1) {
side = " ";
}else {
side = " ";
}
Map<String, String> map = new HashMap<>();
JSONObject jsonObject = JSONObject.parseObject(value);
JSONObject words_result = jsonObject.getJSONObject("words_result");
if (words_result == null || words_result.isEmpty()) {
throw new MyException(" "+side+" ");
}
for (String key : words_result.keySet()) {
JSONObject result = words_result.getJSONObject(key);
String info = result.getString("words");
switch (key) {
case " ":
map.put("name", info);
break;
case " ":
map.put("sex", info);
break;
case " ":
map.put("nation", info);
break;
case " ":
map.put("birthday", info);
break;
case " ":
map.put("address", info);
break;
case " ":
map.put("idNumber", info);
break;
case " ":
map.put("issuedOrganization", info);
break;
case " ":
map.put("issuedAt", info);
break;
case " ":
map.put("expiredAt", info);
break;
}
}
return map;
}
}
공식 반환 예시:신분증 식별 에 큰 구멍 이 있다.
1.어떤 base 64 인 코딩 후 머리"Base 64:"를 제거 하려 면 알 리 바 바 의 base 64 를 정상적으로 사용 할 수 있 습 니 다.
2.OCR 인식 공식 은 그림 을 Base 64 로 인 코딩 해 야 한 다 는 것 만 설명 하지만 실제로는 UrlEncode 를 한 번 더 인 코딩 해 야 한다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.