视觉AI训练营Day02_身份证识别系统搭建
身份证识别系统搭建
开通识别
阿里视觉识别平台https://vision.aliyun.com/,
选择能力广场>文字识别>身份证识别。
开通
源码分析
源码地址:https://github.com/aliyun/alibabacloud-viapi-demo
IDEA打开项目
修改配置application.properties
accessKeyId获取
后台
主要依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>ocr</artifactId>
<version>1.0.3</version>
</dependency>
Controller主要代码
@PostMapping("/upload")
public String uploadFile(@RequestParam("face") MultipartFile face, @RequestParam("back") MultipartFile back, RedirectAttributes attributes) {
if (face.isEmpty() || back.isEmpty()) {
attributes.addFlashAttribute("message", "Please select a file to upload.");
return "redirect:/";
}
String errorMessage = null;
try {
Path dir = Paths.get(uploadDirectory);
if (!Files.exists(dir)) {
Files.createDirectories(dir);
}
if (!face.isEmpty()) {
String filename = saveFile(face);
Map<String, String> res = ocrService.RecognizeIdCard(uploadDirectory + filename, "face");
faceImages.add("/images/" + filename);
faceResults.add(res);
}
if (!back.isEmpty()) {
String filename = saveFile(back);
Map<String, String> res = ocrService.RecognizeIdCard(uploadDirectory + filename, "back");
backImages.add("/images/" + filename);
backResults.add(res);
}
} catch (TeaException e) {
e.printStackTrace();
errorMessage = JSON.toJSONString(e.getData());
} catch (Exception e) {
e.printStackTrace();
errorMessage = e.getMessage();
}
if (StringUtils.isNotBlank(errorMessage)) {
attributes.addFlashAttribute("message", errorMessage);
}
return "redirect:/";
}
Service主要代码
身份认证
@PostConstruct
private void init() throws Exception {
Config config = new Config();
config.type = "access_key";
config.regionId = "cn-shanghai";
config.accessKeyId = accessKeyId;
config.accessKeySecret = accessKeySecret;
config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
ocrClient = new Client(config);
runtime = new RuntimeOptions();
}
返回前端
public Map<String, String> RecognizeIdCard(String filePath, String side) throws Exception {
RecognizeIdentityCardAdvanceRequest request = new RecognizeIdentityCardAdvanceRequest();
request.imageURLObject = Files.newInputStream(Paths.get(filePath));
request.side = side;
RecognizeIdentityCardResponse response = ocrClient.recognizeIdentityCardAdvance(request, runtime);
if ("face".equals(side)) {
return JSON.parseObject(JSON.toJSONString(response.data.frontResult), new TypeReference<Map<String, String>>() {});
} else {
return JSON.parseObject(JSON.toJSONString(response.data.backResult), new TypeReference<Map<String, String>>() {});
}
}
前端
上传选择框限定.jpg, .png, .jpeg
格式
结果输出