通过使用阿里云的OCR图文识别 实现识别功能

这个功能主要是实现一系列的图片识别,例如,驾驶证,身份证等图文信息,首先去阿里云的API中导入相对于的jar包,我是用的pom文件,所以直接导入了:


		
			com.aliyun
			aliyun-java-sdk-core
			4.0.0
		
		
			com.aliyun
			aliyun-java-sdk-green
			3.4.1
		
		
			com.alibaba
			fastjson
			1.2.51
		
		
			com.aliyun.oss
			aliyun-sdk-oss
			2.8.3
		

然后下面是代码实现:

package com.ptpec.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.*;

public class OCRTestAction {

    public static void main(String[] args) throws Exception {
        IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "自己注册的ID", "自己注册的key");
        DefaultProfile
                .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        // 指定api返回格式
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
        // 指定请求方法
        imageSyncScanRequest.setMethod(MethodType.POST);
        imageSyncScanRequest.setEncoding("utf-8");
        //支持http和https
        imageSyncScanRequest.setProtocol(ProtocolType.HTTP);

        JSONObject httpBody = new JSONObject();
        /**
         * 设置要检测的场景
         * ocr: ocr或者ocr卡证识别
         */
        httpBody.put("scenes", Arrays.asList("ocr"));

        /**
         * 设置待检测图片, 一张图片一个task,
         * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
         * 因此通常情况下批量检测的平均rt比单张检测的要长, 一次批量提交的图片数越多,rt被拉长的概率越高
         * 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task
         */
        JSONObject task = new JSONObject();
        task.put("dataId", UUID.randomUUID().toString());

        //设置图片链接
        task.put("url", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1563886821091&di=753344eeb09d5a1e75f182979156b670&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20170910%2F841ee014e42e40c6b562663b2d970577.jpeg");
        task.put("time", new Date());
        httpBody.put("tasks", Arrays.asList(task));

        //ocr卡证识别,设置识别卡证类型
        JSONObject cardExtras = new JSONObject();
        //行驶证正面识别  [可根据官方文档改成其他类型,例如:身份证,可以分为正反面]
        cardExtras.put("card", "vehicle-license-front");
        //行驶证反面
        //cardExtras.put("card", "vehicle-license-back");
        httpBody.put("extras", cardExtras);
        imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()), "UTF-8", FormatType.JSON);
        /**
         * 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置
         * 如果您设置的ReadTimeout 小于服务端处理的时间,程序中会获得一个read timeout 异常
         */
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageSyncScanRequest);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }

        //服务端接收到请求,并完成处理返回的结果
        if(httpResponse != null && httpResponse.isSuccess()){
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            System.out.println(JSON.toJSONString(scrResponse));
            int requestCode = scrResponse.getIntValue("code");
            //每一张图片的检测结果
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    //单张图片的处理结果
                    int taskCode = ((JSONObject)taskResult).getIntValue("code");
                    //图片要检测的场景的处理结果, 如果是多个场景,则会有每个场景的结果
                    JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
                    if(200 == taskCode){
                        for (Object sceneResult : sceneResults) {
                            String scene = ((JSONObject)sceneResult).getString("scene");
                            String suggestion = ((JSONObject)sceneResult).getString("suggestion");
                            //do something
                            //有识别出行驶证信息
                            if("review" .equals(suggestion) && "ocr".equals(scene)){
                                JSONObject idCardInfo =  ((JSONObject) sceneResult).getJSONObject("vehicleLicenseFrontInfo");
                                System.out.println(idCardInfo.toJSONString());
                            }
                        }
                    }else{
                        //单张图片处理失败, 原因是具体的情况详细分析
                        System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                /**
                 * 表明请求整体处理失败,原因视具体的情况详细分析
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
    }
}

 

你可能感兴趣的:(程序人生)