最近作者项目中用到了身份证识别跟营业执照的OCR识别,就研究了一下百度云跟腾讯云的OCR产品接口。

1.腾讯云OCR


收费:身份证OCR和营业执照OCR接口,每个接口每个月各有1000次的免费调用

接口说明:

  1. 身份证OCR接口 -

    https://cloud.tencent.com/document/product/866/33524

  2. 营业执照OCR接口-

    https://cloud.tencent.com/document/product/866/17598

身份证-OCR接入

  1. 引入腾讯的SDK及JSON

  1. <dependency>
  2. <groupId>com.tencentcloudapi</groupId>
  3. <artifactId>tencentcloud-sdk-java</artifactId>
  4. <version>3.0.</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>net.sf.json-lib</groupId>
  8. <artifactId>json-lib</artifactId>
  9. <version>2.4</version>
  10. <classifier>jdk15</classifier>
  11. </dependency>

  2.前端html代码

  1. <form action="/ocr/uploadFile" method="POST" enctype="multipart/form-data">
  2. <input type="file" name="file">
  3. <br />
  4. <input type="radio" name="card_side" value="FRONT"> 正面 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  5. <input type="radio" name="card_side" value="BACK"> 反面
  6. <br />
  7. <input type="submit" value="提交">
  8.  
  9. </form>

  3.后端代码

  1. @PostMapping("uploadFile")
  2. @ResponseBody
  3. public IDCardOCRResponse OCRIdCardTest(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "card_side") String cardSize,Model model){
  4. try {
  5. Credential cred = new Credential("AKIDGQfhYTqEs0DMvUQH93wXKsIX", "7adThzEEH6mK6zg9MMwX0");
  6.  
  7. HttpProfile httpProfile = new HttpProfile();
  8. httpProfile.setEndpoint("ocr.tencentcloudapi.com");
  9.  
  10. ClientProfile clientProfile = new ClientProfile();
  11. clientProfile.setHttpProfile(httpProfile);
  12.  
  13. OcrClient client = new OcrClient(cred, "ap-beijing", clientProfile);
  14. Map<String, String> params = new HashMap<>();
  15. params.put("ImageBase64", getBase64FromInputStream(file.getInputStream()));
  16. params.put("CardSide", cardSize);
  17.  
  18. System.out.println(getBase64FromInputStream(file.getInputStream()));
  19. IDCardOCRRequest req = IDCardOCRRequest.fromJsonString(JSONObject.fromObject(params).toString(), IDCardOCRRequest.class);
  20. IDCardOCRResponse resp = client.IDCardOCR(req);
  21. return resp;
  22. } catch (Exception e) {
  23. // TODO: handle exception
  24. e.printStackTrace();
  25. }
  26. return null;
  27.  
  28. }

说明:new Credential("secretId","secretKey"),这两个参数在腾讯云控制台申请

  4.getBase64FromInputStream代码,把MultipartFile 转为base64

  1. public static String getBase64FromInputStream(InputStream in) {
  2. // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  3. byte[] data = null;
  4. // 读取图片字节数组
  5. try {
  6. ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
  7. byte[] buff = new byte[100];
  8. int rc = 0;
  9. while ((rc = in.read(buff, 0, 100)) > 0) {
  10. swapStream.write(buff, 0, rc);
  11. }
  12. data = swapStream.toByteArray();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. } finally {
  16. if (in != null) {
  17. try {
  18. in.close();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. return new String(Base64.encodeBase64(data));
  25. }

运行前端html码,选择身份证图片,点击提交就可以返回身份证的信息了。

营业执照-OCR

1.前端html代码

  1. <form action="/ocr/bizlicense" method="POST" enctype="multipart/form-data">
  2. <input type="file" name="file">
  3. <br />
  4.  
  5. <input type="submit" value="提交">
  6.  
  7. </form>

2.后端代码

  1. @PostMapping("bizlicense")
  2. @ResponseBody
  3. public String OCRBizlicenseTest(@RequestParam(value = "file") MultipartFile file) throws Exception{
  4. RestTemplate restTemplate = new RestTemplate();
  5. String apiUrl="https://recognition.image.myqcloud.com/ocr/bizlicense";
  6. HttpHeaders headers = new HttpHeaders();
  7. headers.set("host", "recognition.image.myqcloud.com");
  8. headers.set("content-type", "application/json");
  9. String authorization=QQOCRSignUtils.appSign(XXXX, "AKIDGQfhYTqEs0DXXX", "7adThzEEH6mKXXX", "", 10L);
  10. headers.set("authorization",authorization );
  11.  
  12. JSONObject params = new JSONObject();
  13. params.put("appid", "XXX");
  14. params.put("image", getBase64FromInputStream(file.getInputStream()));
  15. HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(params, headers);
  16. HttpEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
  17. return response.getBody();
  18. }

3.QQOCRSignUtils.appSign

  1. /**
  2. * 生成 Authorization 签名字段
  3. *
  4. * @param appId
  5. * @param secretId
  6. * @param secretKey
  7. * @param bucketName
  8. * @param expired
  9. * @return
  10. * @throws Exception
  11. */
  12. public static String appSign(long appId, String secretId, String secretKey, String bucketName,
  13. long expired) throws Exception {
  14. long now = System.currentTimeMillis() / 1000;
  15. int rdm = Math.abs(new Random().nextInt());
  16. String plainText = String.format("a=%d&b=%s&k=%s&t=%d&e=%d&r=%d", appId, bucketName,
  17. secretId, now, now + expired, rdm);
  18. byte[] hmacDigest = HmacSha1(plainText, secretKey);
  19. byte[] signContent = new byte[hmacDigest.length + plainText.getBytes().length];
  20. System.arraycopy(hmacDigest, 0, signContent, 0, hmacDigest.length);
  21. System.arraycopy(plainText.getBytes(), 0, signContent, hmacDigest.length,
  22. plainText.getBytes().length);
  23. return Base64Encode(signContent);
  24. }

运行前端html码,选择营业执照图片,点击提交就可以返回营业执照的信息了。

2.百度OCR


通过以下步骤创建OCR应用,作者当时在这一步花了很长时间

创建完之后就可以拿到appId,API Key,Secret Key,就可以调用百度提供的api了

收费:身份证OCR和营业执照OCR接口,每个接口每天各有500次的免费调用

接口说明:

  1. 身份证OCR接口 -

    https://cloud.baidu.com/doc/OCR/OCR-API.html#.E8.BA.AB.E4.BB.BD.E8.AF.81.E8.AF.86.E5.88.AB

  2. 营业执照OCR接口-

    https://cloud.baidu.com/doc/OCR/OCR-API.html#.E8.90.A5.E4.B8.9A.E6.89.A7.E7.85.A7.E8.AF.86.E5.88.AB

 

身份证OCR 

只列出后端的代码,前端代码跟腾讯的一样,只不过前后面身份证枚举值不一样,参考接口文档说明。

  1. @PostMapping("ocridcard")
  2. @ResponseBody
  3. public String OCRIdCardTest(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "card_side") String cardSize,Model model){
  4. try {
  5. RestTemplate restTemplate = new RestTemplate();
  6. HttpEntity<String> response = restTemplate.postForEntity("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=XXXXXX&client_secret=XXXXXX",null,String.class);
  7. JSONObject jsonObject = JSONObject.fromObject(response.getBody());
  8. System.out.println(response.getBody());
  9. String accessToken = jsonObject.getString("access_token");
  10.  
  11. String apiUrl="https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="+accessToken;
  12. HttpHeaders headers = new HttpHeaders();
  13. headers.set("content-type", "application/x-www-form-urlencoded");
  14.  
  15. MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
  16. params.add("detect_direction", "true");
  17. params.add("id_card_side", cardSize);
  18. params.add("image", Base64Utils.getBase64FromInputStream(file.getInputStream()));
  19. params.add("detect_risk", "true");
  20. System.out.println(Base64Utils.getBase64FromInputStream(file.getInputStream()));
  21. System.out.println(URLDecoder.decode(URLEncoder.encode(Base64Utils.getBase64FromInputStream(file.getInputStream()),"UTF-8"),"UTF-8"));
  22. HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);
  23. response = restTemplate.postForEntity(apiUrl, entity, String.class);
  24. return response.getBody();
  25.  
  26. } catch (Exception e) {
  27. // TODO: handle exception
  28. e.printStackTrace();
  29. }
  30. return null;
  31.  
  32. }

营业执照OCR

  1. @PostMapping("ocrbusinesslicense")
  2. @ResponseBody
  3. public String OCRBusinessLicenseTest(@RequestParam(value = "file") MultipartFile file,Model model){
  4. try {
  5. RestTemplate restTemplate = new RestTemplate();
  6. HttpEntity<String> response = restTemplate.postForEntity("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=XXXXX&client_secret=XXXXXX",null,String.class);
  7. JSONObject jsonObject = JSONObject.fromObject(response.getBody());
  8. System.out.println(response.getBody());
  9. String accessToken = jsonObject.getString("access_token");
  10.  
  11. String apiUrl="https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token="+accessToken;
  12. HttpHeaders headers = new HttpHeaders();
  13. headers.set("content-type", "application/x-www-form-urlencoded");
  14.  
  15. MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
  16. params.add("detect_direction", "true");
  17. params.add("image", Base64Utils.getBase64FromInputStream(file.getInputStream()));
  18.  
  19. System.out.println(Base64Utils.getBase64FromInputStream(file.getInputStream()));
  20. System.out.println(URLDecoder.decode(URLEncoder.encode(Base64Utils.getBase64FromInputStream(file.getInputStream()),"UTF-8"),"UTF-8"));
  21. HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);
  22. response = restTemplate.postForEntity(apiUrl, entity, String.class);
  23. return response.getBody();
  24.  
  25. } catch (Exception e) {
  26. // TODO: handle exception
  27. e.printStackTrace();
  28. }
  29. return null;
  30.  
  31. }
作者:Eric.Chen
出处:https://www.cnblogs.com/lc-chenlong

如果喜欢作者的文章,请关注“写代码的猿”订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载

OCR识别的更多相关文章

  1. Atitit  ocr识别原理 与概论 attilax总结

    Atitit  ocr识别原理 与概论 attilax总结 1.1. Ocr的过程与流程1 1.2. OCR不同技术细分略有不同,但大概原理是一样的. 即主要技术过程是:二值化(又叫归一化)----- ...

  2. 基于Python实现对PDF文件的OCR识别

    http://www.jb51.net/article/89955.htm https://pythontips.com/2016/02/25/ocr-on-pdf-files-using-pytho ...

  3. OCR识别-python版(一)

    需求:识别图片中的文字信息环境:windows系统 开发语言:python 使用工具类:1.pyocr 2.PIL 3.tesseract-ocr 步骤: 1.pyocr 网络通直接使用命令:pip ...

  4. 汽车Vin码识别——可以嵌入到手机里的新OCR识别技术

              汽车Vin码识别(车架号识别),顾名思义,就是识别汽车的Vin码(车架号),汽车Vin码识别(车架号识别)利用的是OCR识别技术,支持视频流获取图像,自动触发识别,另外汽车Vin码 ...

  5. 汽车Vin码识别—— 一款二手车行业值得拥有的OCR识别软件

    一.汽车Vin码识别产品描述 汽车Vin码识别系统,主要应用在智能手机IOS与Android两个平台中.前端扫描查询模式,无需联网,只需扫描汽车前挡风玻璃右下角的Vin码(车架号),即可轻松识别出车辆 ...

  6. 发票OCR识别/票据OCR自动识别

    对于一些大的集团公司来说,分散式财务管理模式管理效率不高,管理成本相对较高,同时也制约了集团企业发展战略的实施,因而需要建设财务共享中心.一个企业想建造财务共享中心,面临的难题是大量的数据采集和信息处 ...

  7. 采用OCR识别自动识别财务报表

    一.         财务报表有什么作用 财务报表又叫会计报表,包含:资产负债表.损益表.现金流量表三表.财务报表对企业经营状况有重要的参考意义: n  全面系统地揭示企业一定时期的财务状况.经营成果 ...

  8. 深入浅出了解OCR识别票据原理(Applying OCR Technology for Receipt Recognition)

    原文:Applying OCR Technology for Receipt Recognition 译文:深入浅出了解OCR识别票据原理 英文票据识别技术, 非中文票据识别技术, 中文情况的ocr更 ...

  9. 以API方式调用C# dll,使用OneNote2013 sp1实现OCR识别本地图片

    http://www.cnblogs.com/Charltsing/p/OneNoteOCRAPI.html OneNote2013 OCR API调用使用说明2019.4.17 使用说明:1.安装干 ...

随机推荐

  1. LocalDate、LocalDateTime、LocalTime开发小结

    在我之前的文章<[整理]Java 8新特性总结 >中有提到Date/Time API (JSR 310)对日期与时间的处理.它将服务端对时间的处理进行了统一,使得对时间的处理更加规范和统一 ...

  2. 181102 Python环境搭建(安装Sublime Text3)

    利用Pycharm来编写.执行python代码是一个不错的选择,Pycharm的安装的确也很方便.但是偶然看到别人用Sublime Text来编写.执行代码,觉得很酷.所以自己动手搭建环境. 1. 下 ...

  3. sass快速入门

    sass十分钟入门 变量 sass中可以定义变量,方便统一修改和维护. //sass style //----------------------------------- $fontStack: H ...

  4. Docker-Compose入门

    转:https://blog.csdn.net/chinrui/article/details/79155688

  5. LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++>

    LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++> 给出排序好的一维有重复元素的数组,随机取一个位置断开 ...

  6. 《SpringMVC从入门到放肆》七、模型与视图ModelAndView

    上一篇我们了解了开发一个Controller的4种方法,如果不记得的朋友可以看看上一篇博文,今天我们来继续了解SpringMVC的模型与视图ModelAndView. 一.什么是Model? Mode ...

  7. vue变异方法

    push()  往数组最后面添加一个元素,成功返回当前数组的长度    pop()  删除数组的最后一个元素,成功返回删除元素的值    shift()  删除数组的第一个元素,成功返回删除元素的值u ...

  8. Swift 对象内存模型探究(一)

    本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:https://mp.weixin.qq.com/s/zIkB9KnAt1YPWGOOwyqY3Q 作者:王 ...

  9. [.net 面向对象程序设计深入](31)实战设计模式——使用Ioc模式(控制反转或依赖注入)实现松散耦合设计(1)

    [.net 面向对象程序设计深入](31)实战设计模式——使用IoC模式(控制反转或依赖注入)实现松散耦合设计(1) 1,关于IOC模式 先看一些名词含义: IOC: Inversion of con ...

  10. JDK的下载,安装,环境变量配置

    JDK 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html 环境变量配置:在"系统变量" ...