OCR文字识别

使用代码调用OCR服务

更新时间:2024-08-26 16:25:55

本文提供了通过代码快速调用 OCR 通用文字识别API的样例,帮助您通过简单的编码编写快速熟悉并使用文字识别服务。

1.Python示例

-- 获取token --

import requests, json, hashlib

def signature(appid, appkey, timestamp, nonce):
    """
    sha256获取签名
    :param appid:
    :param appkey:
    :param timestamp:yyyyMMddHHmmss时间戳
    :param nonce: 18位随机数
    :return:
    """
    param = appid + timestamp + nonce + appkey
    param = param.encode("utf-8")
    hash_value = hashlib.sha256(param).hexdigest()
    return hash_value


if __name__ == '__main__':
    appid = "10037e6f82649bb20182aa95eeaf0031"
    appkey = "6e21ae0f08034b8086f6e0c533c8f742"
    timestamp = "20230823181923"
    nonce = "882mg2uwji5jzcg2jz"

    data = json.dumps({
        "appId": appid,
        "timestamp": timestamp,
        "nonce": nonce,
        "signMethod": "SHA256",
        "signature": signature(appid, appkey, timestamp, nonce)
    })

    url = r"https://test-api-open.chinaums.com/v1/token/access"  # 测试
    # url = r"https://api-mop.chinaums.com/v1/token/access"  # 生产

    headers = {"Content-Type": "application/json"}
    res = requests.post(url, data=data, headers=headers)
    print(res.text)

-- 利用token进行OCR识别 --

import requests, json
import pic2b64

# 填写身份证的测试环境地址、样例图片路径
url = "http://test-api-open.chinaums.com/v1/brain/ocr/idcard"
img_path = r"D:\OCR\xxxxxx\idcard.jpg"

data = json.dumps({"picBase64": pic2b64.pic2b64(img_path)})
headers = {
    "Authorization": "OPEN-ACCESS-TOKEN AccessToken=a60e0024c50841a3ae9865a0ddf651fa"
}
res = requests.post(url, data=data, headers=headers)
print(res.json())

2.Java示例

util/AuthorizeUtils.java

package yuewu.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class AuthorizeUtils {
    private static final String TEST_URL = "https://test-api-open.chinaums.com/v2/token/access";
    private static final String PROD_URL = "https://api-mop.chinaums.com/v2/token/access";

    /**
     * 获取认证 OPEN-BODY-SIG
     *
     * @param appId  appId
     * @param appKey appKey
     * @param body   请求体
     * @return authorization 认证报文
     * @throws Exception Exception
     */
    public static String getAuthByOpenBodySig(String appId, String appKey, String timestamp, String nonce, String body) throws Exception {
        String localSignatureStr = getSignature(appId, appKey, timestamp, nonce, body);
        return "OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"";
    }

    public static String getAuthByAccessToken(String appId, String appKey, String timestamp, String nonce) {
        String sign = DigestUtils.sha1Hex(appId + timestamp + nonce + appKey);
        String body = buildTokenParam(appId, timestamp, nonce, sign);
        String response = RequestUtils.post(TEST_URL, null, body);
        JSONObject respJson = JSONObject.parseObject(response);
        return "OPEN-ACCESS-TOKEN AccessToken=" + respJson.getString("accessToken") + "";
    }

    public static String getSignature(String appId, String appKey, String timestamp, String nonce, String body) throws Exception {
        byte[] data = body.getBytes(StandardCharsets.UTF_8);
        InputStream is = new ByteArrayInputStream(data);
        String testSH = DigestUtils.sha256Hex(is);
        String s1 = appId + timestamp + nonce + testSH;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(appKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] localSignature = mac.doFinal(s1.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(localSignature);
    }

    private static String buildTokenParam(String appId, String timestamp, String nonce, String signature) {
        Map<String, String> map = new HashMap<>();
        map.put("appId", appId);
        map.put("timestamp", timestamp);
        map.put("nonce", nonce);
        map.put("signature", signature);
        return JSONObject.toJSONString(map);
    }
}

util/RequestUtils.java

package yuewu.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

public class RequestUtils {
    /**
     * 发送http请求
     *
     * @param url           请求url
     * @param authorization 认证报文
     * @param reqBody       请求体
     * @return response
     */
    public static String post(String url, String authorization, String reqBody) {
        StringBuilder response = new StringBuilder();
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestProperty("Content-Type", "application/json");
            httpUrlConnection.setRequestProperty("authorization", authorization);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            out = new PrintWriter(httpUrlConnection.getOutputStream());
            out.write(reqBody);
            out.flush();
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response.toString();
    }

    /**
     * 发送httpGET请求
     *
     * @param url 请求url
     * @return response
     */
    public static String get(String url) {
        StringBuilder sb = new StringBuilder();
        String response = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setReadTimeout(15000);
            httpUrlConnection.setReadTimeout(60000);
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            response = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }
}

BrainOcrDemo.java

package yuewu;

import yuewu.util.AuthorizeUtils;
import yuewu.util.RequestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class BrainOcrDemo {
    private static final String APPID = "10037e6f81d2544a0181d793a9190000";
    private static final String APPKEY = "ba6e723428584f0aab6afea43a224980";
    private static final String URL = "https://test-api-open.chinaums.com/v1/brain/ocr/idcard";


    public static void main(String[] args) throws Exception {
        RequestBody reqBody = new RequestBody();
        reqBody.isHeadImage = false;
        reqBody.picBase64 = "base64Value";
        System.out.println(reqBody);

        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String nonce = UUID.randomUUID().toString().replace("-", "");
        String authorization = AuthorizeUtils.getAuthByAccessToken(APPID, APPKEY, timestamp, nonce);
        System.out.println("Authorization: " + authorization);
  
        // 3. 发送http请求,并解析返回信息
        String response = RequestUtils.post(URL, authorization, reqBody.toString());
        System.out.println("response: " + response);
    }

    static class RequestBody {
        Boolean isHeadImage;
        String picBase64;


        String toJSON() {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            if (this.isHeadImage != null) sb.append("\"isHeadImage\":\"").append(this.isHeadImage).append("\",");
            if (this.picBase64 != null) sb.append("\"picBase64\":\"").append(this.picBase64).append("\",");
            if (sb.charAt(sb.length() - 1) == ',')
                sb.deleteCharAt(sb.length() - 1);
            sb.append("}");
            return sb.toString();
        }

        public String toString() {
            return this.toJSON();
        }
    }
}

< 上一篇:使用Postman调用OCR服务
下一篇: 计费概述 >