視覺AI訓練營Day02_身份證識別系統搭建
阿新 • • 發佈:2020-11-28
身份證識別系統搭建
開通識別
阿里視覺識別平臺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
格式
結果輸出