热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

阿里云印刷文字识别营业执照识别

阿里云营业执照识别API最近有由于需要,我开始接触阿里云的云市场的印刷文字识别-营业执照识别这里我加上了官网的申请说明,只要你有阿里云账号就可以用&#

阿里云营业执照识别API

最近有由于需要,我开始接触阿里云的云市场的印刷文字识别-营业执照识别这里我加上了官网的申请说明,只要你有阿里云账号就可以用,前500次是免费的,API说明很简陋,只能做个简单参考。


一、API介绍

api介绍
JAVA示例:

public static void main(String[] args) {String host = "https://dm-58.data.aliyun.com";String path = "/rest/160601/ocr/ocr_business_license.json";String method = "POST";String appcode = "你自己的AppCode";Map headers = new HashMap();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);//根据API的要求,定义相对应的Content-Typeheaders.put("Content-Type", "application/json; charset=UTF-8");Map querys = new HashMap();String bodys = "{\"image\":\"对图片内容进行Base64编码\"}";try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);System.out.println(response.toString());//获取response的body//System.out.println(EntityUtils.toString(response.getEntity()));} catch (Exception e) {e.printStackTrace();}}

返回码:

{"config_str" : "null\n", #配置字符串信息"angle" : float, #输入图片的角度(顺时针旋转),[0, 90, 180,270]"reg_num" : string, #注册号,没有识别出来时返回"FailInRecognition""name" : string, #公司名称,没有识别出来时返回"FailInRecognition""type" : string, #公司类型,没有识别出来时返回"FailInRecognition""person" : string, #公司法人,没有识别出来时返回"FailInRecognition""establish_date": string, #公司注册日期(例:证件上为"2014年04月16日",算法返回"20140416")"valid_period": string, #公司营业期限终止日期(例:证件上为"2014年04月16日至2034年04月15日",算法返回"20340415")#当前算法将日期格式统一为输出为"年月日"(如"20391130"),并将"长期"表示为"29991231",若证件上没有营业期限,则默认其为"长期",返回"29991231"。"address" : string, #公司地址,没有识别出来时返回"FailInRecognition""capital" : string, #注册资本,没有识别出来时返回"FailInRecognition""business": string, #经营范围,没有识别出来时返回"FailInRecognition""emblem" : string, #国徽位置[top,left,height,width],没有识别出来时返回"FailInDetection""title" : string, #标题位置[top,left,height,width],没有识别出来时返回"FailInDetection""stamp" : string, #印章位置[top,left,height,width],没有识别出来时返回"FailInDetection""qrcode" : string, #二维码位置[top,left,height,width],没有识别出来时返回"FailInDetection""success" : bool, #识别成功与否 true/false"request_id": string
}

购买后,在云市场列表里展示,你可要点击进去查看AppCode等其主要信息(接口调用里需要AppCode)
在这里插入图片描述

简单的API介绍,但挺有效了的,唯一不好的就是没有错误返回码的描述,需要自己测试。


二、代码开发

闲话少说,上代码:


  1. AliyunImageRecognitionUtil :阿里云图像识别工具类

package com.casic.cloud.qcy.util;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;import com.alibaba.fastjson.JSONObject;
import com.casic.cloud.qcy.constant.Constants;import sun.misc.BASE64Encoder;/** * @ClassName: AliyunImageRecognitionUtil * @Description: 阿里云图像识别工具类* @author: tianpengw* @date 2019年3月21日 上午8:49:08 * */
public class AliyunImageRecognitionUtil {private static String businessLicenceHost = PropertiesUtil.getProperties("businessLicenceHost");private static String businessLicencePath = PropertiesUtil.getProperties("businessLicencePath");private static String method = "POST";private static String appCode = PropertiesUtil.getProperties("appCode");/*** * @Description: 根据文件全路径识别* @author: tianpengw* @param imgPath* @return*/public static Map bussinessLicenceRecognition(String imgPath){Map resultMap = new HashMap();Map headers = new HashMap();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appCode);headers.put("Content-Type", "application/json; charset=UTF-8");Map querys = new HashMap();String bodys = "{\"image\":\""+imageToBase64Str(imgPath)+"\"}";try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = AliyunHttpUtils.doPost(businessLicenceHost, businessLicencePath, method, headers, querys, bodys);String resStr = EntityUtils.toString(response.getEntity());System.out.println(resStr);resultMap = JSONObject.parseObject(resStr, Map.class);//获取response的body} catch (Exception e) {e.printStackTrace();}return resultMap;}/*** * @Description: 根据InputStream识别* @author: tianpengw* @param imgPath* @return*/public static Map bussinessLicenceRecognition(InputStream inputStream){Map resultMap = new HashMap();Map headers = new HashMap();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appCode);headers.put("Content-Type", "application/json; charset=UTF-8");Map querys = new HashMap();// 加密BASE64Encoder encoder = new BASE64Encoder();byte[] data = null;try {data = new byte[inputStream.available()];inputStream.read(data);inputStream.close();} catch (IOException e) {e.printStackTrace();}String bodys = "{\"image\":\""+encoder.encode(data)+"\"}";try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = AliyunHttpUtils.doPost(businessLicenceHost, businessLicencePath, method, headers, querys, bodys);String resStr = EntityUtils.toString(response.getEntity());System.out.println(resStr);resultMap = JSONObject.parseObject(resStr, Map.class);resultMap.put("errCode", Constants.RESULT_SUCCESS);//获取response的body} catch (Exception e) {e.printStackTrace();resultMap.put("errCode", Constants.RESULT_FAIL);}return resultMap;}/*** * @Description: 根据byte[]识别* @author: tianpengw* @param imgPath* @return*/public static Map bussinessLicenceRecognition( byte[] data){Map resultMap = new HashMap();Map headers = new HashMap();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appCode);headers.put("Content-Type", "application/json; charset=UTF-8");Map querys = new HashMap();// 加密BASE64Encoder encoder = new BASE64Encoder();String bodys = "{\"image\":\""+encoder.encode(data)+"\"}";try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = AliyunHttpUtils.doPost(businessLicenceHost, businessLicencePath, method, headers, querys, bodys);String resStr = EntityUtils.toString(response.getEntity());System.out.println(resStr);resultMap = JSONObject.parseObject(resStr, Map.class);resultMap.put("errCode", Constants.RESULT_SUCCESS);//获取response的body} catch (Exception e) {e.printStackTrace();resultMap.put("errCode", Constants.RESULT_FAIL);}return resultMap;}/*** 图片转base64字符串* @param imgFile 图片路径* @return*/public static String imageToBase64Str(String imgFile) {InputStream inputStream = null;byte[] data = null;try {inputStream = new FileInputStream(imgFile);data = new byte[inputStream.available()];inputStream.read(data);inputStream.close();} catch (IOException e) {e.printStackTrace();}// 加密BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);}public static void main(String[] args) {String imgPath = "d:/yyzznew1.jpg";Map map = AliyunImageRecognitionUtil.bussinessLicenceRecognition(imgPath);System.out.println(map.get("person"));System.out.println(map.get("reg_num"));}
}

  1. AliyunHttpUtils :阿里云httpUtils

package com.casic.cloud.qcy.util;import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;/** * @ClassName: AliyunHttpUtils * @Description: * @author: tianpengw* @date 2019年3月21日 上午8:44:51 * */
public class AliyunHttpUtils {/*** get* * @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doGet(String host, String path, String method, Map headers, Map querys)throws Exception { HttpClient httpClient = wrapClient(host);HttpGet request = new HttpGet(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** post form* * @param host* @param path* @param method* @param headers* @param querys* @param bodys* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method, Map headers, Map querys, Map bodys)throws Exception { HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (bodys != null) {List nameValuePairList = new ArrayList();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");request.setEntity(formEntity);}return httpClient.execute(request);} /*** Post String* * @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method, Map headers, Map querys, String body)throws Exception { HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Post stream* * @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method, Map headers, Map querys, byte[] body)throws Exception { HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Put String* @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method, Map headers, Map querys, String body)throws Exception { HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Put stream* @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method, Map headers, Map querys, byte[] body)throws Exception { HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Delete* * @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doDelete(String host, String path, String method, Map headers, Map querys)throws Exception { HttpClient httpClient = wrapClient(host);HttpDelete request = new HttpDelete(buildUrl(host, path, querys));for (Map.Entry e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException {StringBuilder sbUrl = new StringBuilder();sbUrl.append(host);if (!StringUtils.isBlank(path)) {sbUrl.append(path);}if (null != querys) {StringBuilder sbQuery = new StringBuilder();for (Map.Entry query : querys.entrySet()) {if (0 }

  1. PropertiesUtil :读取配置文件工具

package com.casic.cloud.qcy.util;import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;/** * @ClassName: PropertiesUtil * @Description: * @author tianpengw* @date 2018年6月27日 下午3:09:08 * */
public class PropertiesUtil {private static Logger log = LogManager.getLogger(PropertiesUtil.class);private static Properties prop;static{try{if(null == prop){prop = new Properties();}InputStream fis = null;fis = ClassLoaderUtils.getResourceAsStream("common.properties", PropertiesUtil.class);if(fis!=null){prop.load(fis);// 将属性文件流装载到Properties对象中 fis.close();// 关闭流 }}catch (Exception e) {log.error("读取配置文件出错:" + e );}}/*** * @Description: 根据key获取配置的值* @author tianpengw * @param key* @return*/public static String getProperties(String key){if(key==null) return null;return prop.getProperty(key);}/*** * @Description: * @author tianpengw * @param proper 读取配置的文件名称* @param key* @return*/public static String getPropertie(String resourceName,String key){InputStream fis = ClassLoaderUtils.getResourceAsStream(resourceName, PropertiesUtil.class);if(fis!=null){try {prop.load(fis);fis.close();// 关闭流 } catch (IOException e) {e.printStackTrace();} }if(key==null) return null;return prop.getProperty(key);}/*** * @Description: 根据key获取配置的值,若没有,则取传过来的默认的值* @author tianpengw * @param key* @param defaultValue 默认值* @return*/public static String getProperties(String key,String defaultValue){if(key==null) return null;return prop.getProperty(key, defaultValue);}
}

  1. 配置文件common.properties(放在 src/main/resources下)

#aliyun business licence recognition
businessLicenceHost = https://dm-58.data.aliyun.com
businessLicencePath = /rest/160601/ocr/ocr_business_license.json
appCode = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

三、测试结果


  1. 成功的结果:
    在这里插入图片描述
  2. 失败结果,当处理非营业执照的图片时将会返回“invalid business licence”结果,我这么没有进行判断处理直接按照正确的json解析,所以报错,此处你们可以按照自己需求选择处理逻辑。从这返回结果也看的出该接口做的不合理,返回内容不统一,导致接口使用者,必须知晓各种情况才能做有效的处理,如果此处能返回json串,给错误码那对于调用者来说就方便多了。
    在这里插入图片描述

四、后记


  1. 此API适合一般的营业执照和新的三证合一的营业执照,但是字段获取的含义不同,此处需要注意;
  2. 由于API并未列出错误码,在未知的错误情况还包含识别次数不够的时候是报错还是有错误提示(由于条件限制,此情况无法验证);
  3. 工具是死的,人是活的,开发需要考虑尽可能多的情况,来保证代码的完善。

至此,工具介绍完毕,欢迎交流。


推荐阅读
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • Android实战——jsoup实现网络爬虫,糗事百科项目的起步
    本文介绍了Android实战中使用jsoup实现网络爬虫的方法,以糗事百科项目为例。对于初学者来说,数据源的缺乏是做项目的最大烦恼之一。本文讲述了如何使用网络爬虫获取数据,并以糗事百科作为练手项目。同时,提到了使用jsoup需要结合前端基础知识,以及如果学过JS的话可以更轻松地使用该框架。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
  • 本文介绍了RxJava在Android开发中的广泛应用以及其在事件总线(Event Bus)实现中的使用方法。RxJava是一种基于观察者模式的异步java库,可以提高开发效率、降低维护成本。通过RxJava,开发者可以实现事件的异步处理和链式操作。对于已经具备RxJava基础的开发者来说,本文将详细介绍如何利用RxJava实现事件总线,并提供了使用建议。 ... [详细]
author-avatar
张晓和46872
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有