最近作者项目中用到了身份证识别跟营业执照的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

<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.0.</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

  2.前端html代码

<form action="/ocr/uploadFile" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br />
<input type="radio" name="card_side" value="FRONT"> 正面 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="card_side" value="BACK"> 反面
<br />
<input type="submit" value="提交"> </form>

  3.后端代码

@PostMapping("uploadFile")
@ResponseBody
public IDCardOCRResponse OCRIdCardTest(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "card_side") String cardSize,Model model){
try {
Credential cred = new Credential("AKIDGQfhYTqEs0DMvUQH93wXKsIX", "7adThzEEH6mK6zg9MMwX0"); HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("ocr.tencentcloudapi.com"); ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile); OcrClient client = new OcrClient(cred, "ap-beijing", clientProfile);
Map<String, String> params = new HashMap<>();
params.put("ImageBase64", getBase64FromInputStream(file.getInputStream()));
params.put("CardSide", cardSize); System.out.println(getBase64FromInputStream(file.getInputStream()));
IDCardOCRRequest req = IDCardOCRRequest.fromJsonString(JSONObject.fromObject(params).toString(), IDCardOCRRequest.class);
IDCardOCRResponse resp = client.IDCardOCR(req);
return resp;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null; }

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

  4.getBase64FromInputStream代码,把MultipartFile 转为base64

public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new String(Base64.encodeBase64(data));
}

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

营业执照-OCR

1.前端html代码

<form action="/ocr/bizlicense" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br /> <input type="submit" value="提交"> </form>

2.后端代码

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

3.QQOCRSignUtils.appSign

/**
* 生成 Authorization 签名字段
*
* @param appId
* @param secretId
* @param secretKey
* @param bucketName
* @param expired
* @return
* @throws Exception
*/
public static String appSign(long appId, String secretId, String secretKey, String bucketName,
long expired) throws Exception {
long now = System.currentTimeMillis() / 1000;
int rdm = Math.abs(new Random().nextInt());
String plainText = String.format("a=%d&b=%s&k=%s&t=%d&e=%d&r=%d", appId, bucketName,
secretId, now, now + expired, rdm);
byte[] hmacDigest = HmacSha1(plainText, secretKey);
byte[] signContent = new byte[hmacDigest.length + plainText.getBytes().length];
System.arraycopy(hmacDigest, 0, signContent, 0, hmacDigest.length);
System.arraycopy(plainText.getBytes(), 0, signContent, hmacDigest.length,
plainText.getBytes().length);
return Base64Encode(signContent);
}

运行前端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 

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

@PostMapping("ocridcard")
@ResponseBody
public String OCRIdCardTest(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "card_side") String cardSize,Model model){
try {
RestTemplate restTemplate = new RestTemplate();
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);
JSONObject jsonObject = JSONObject.fromObject(response.getBody());
System.out.println(response.getBody());
String accessToken = jsonObject.getString("access_token"); String apiUrl="https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="+accessToken;
HttpHeaders headers = new HttpHeaders();
headers.set("content-type", "application/x-www-form-urlencoded"); MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("detect_direction", "true");
params.add("id_card_side", cardSize);
params.add("image", Base64Utils.getBase64FromInputStream(file.getInputStream()));
params.add("detect_risk", "true");
System.out.println(Base64Utils.getBase64FromInputStream(file.getInputStream()));
System.out.println(URLDecoder.decode(URLEncoder.encode(Base64Utils.getBase64FromInputStream(file.getInputStream()),"UTF-8"),"UTF-8"));
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);
response = restTemplate.postForEntity(apiUrl, entity, String.class);
return response.getBody(); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null; }

营业执照OCR

@PostMapping("ocrbusinesslicense")
@ResponseBody
public String OCRBusinessLicenseTest(@RequestParam(value = "file") MultipartFile file,Model model){
try {
RestTemplate restTemplate = new RestTemplate();
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);
JSONObject jsonObject = JSONObject.fromObject(response.getBody());
System.out.println(response.getBody());
String accessToken = jsonObject.getString("access_token"); String apiUrl="https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token="+accessToken;
HttpHeaders headers = new HttpHeaders();
headers.set("content-type", "application/x-www-form-urlencoded"); MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("detect_direction", "true");
params.add("image", Base64Utils.getBase64FromInputStream(file.getInputStream())); System.out.println(Base64Utils.getBase64FromInputStream(file.getInputStream()));
System.out.println(URLDecoder.decode(URLEncoder.encode(Base64Utils.getBase64FromInputStream(file.getInputStream()),"UTF-8"),"UTF-8"));
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);
response = restTemplate.postForEntity(apiUrl, entity, String.class);
return response.getBody(); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null; }
作者: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. BZOJ.5397.circular(随机化 贪心)

    BZOJ 感觉自己完全没做过环上选线段的问题(除了一个2-SAT),所以来具体写一写qwq. 基本完全抄自remoon的题解qwq... (下标从\(0\sim m-1\)) 拆环为链,对于原线段\( ...

  2. Web端常见问题总结

    1.ES6箭头函数和普通函数的区别(至少3点) (1)箭头函数的this永远指向其上下文的 this,任何方法都改变不了其指向,如call(), bind(), apply(),普通函数的this指向 ...

  3. VUE 一些环境配置

    1. 安装  nrm 一键切换npm源 npm i nrm -g       [安装命令工具] nrm ls                 [罗列出所有的源] nrm use taobao  [使用 ...

  4. python入门 -- 环境搭建(windows)

    1. 下载Anaconda Anaconda内置了python解释器及经常使用的库,提供了编译好的环境.根据自己的操作系统,自行从下面网站挑选一个较新的版本,下载安装即可. https://mirro ...

  5. wait event & wake up

    在linux驱动中一个常用的场景, 驱动需要等待中断的响应, 才得以执行后续的代码,达到一个原子操作的目的 /* 静态申请队列 */ static DECLARE_WAIT_QUEUE_HEAD(s_ ...

  6. Redis sentinel 哨兵模式

    一.sentinel介绍 Sentinel作用: 1):Master状态检测 2):如果Master异常,则会进行Master-Slave切换,将其中一个Slave作为Master,将之前的Maste ...

  7. 记录 制作校园网登陆脚本 python编写 附源码

    ‘’‘ 首先我们分析一下 1.需要本机的IP 使用 socket 获取 2.需要向服务器提交的数据 构造请求数据 并分析数据可替换 3.检测登陆成功 检测登陆是否成功 ’‘’ 获取IP 这样会返回 本 ...

  8. java中int和integer

  9. 前端系列——jquery.i18n.properties前端国际化解决方案“填坑日记”

    前言:最近,新的平台还没有开发完成,原来的老项目又提出了新的需求:系统国际化.如果是前后端完全分离的开发模式,要做国际化,真的太简单了,有现成的解决方案,基于Node构建的时下热门的任何一种技术选型都 ...

  10. Java面试题:Hibernate的二级缓存与Hibernate多表查询

    我们来看两个有关Java框架之Hibernate的面试题,这是关于Hibernate的常考知识点. 1.请介绍一下Hibernate的二级缓存 解题按照以下思路来回答: (1)首先说清楚什么是缓存: ...