腾讯文字识别API使用

使用java调用腾讯的文字识别api,将返回结果进行拼接,以及错误日志的记录,日志的记录不会覆盖之前的内容

使用说明

  • 去腾讯云官网注册账号,替换代码里面的secretId和secretKey,每月可以免费请求1000次
  • 上传的图片不能超过5M
  • 接口的原始返回结果保存在response.txt里面
  • 文字拼接后的结果在content.txt里面
  • 识别率小于90%的,认为是错别字,保存在wrongChars.txt里面
  • 腾讯接口文档

jar包依赖

<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>3.1.595</version>
</dependency>

代码实现

package com.example.springboot01;

import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import org.junit.Test;
import org.junit.platform.commons.util.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.example.springboot01.util.Base64Util.GetImageStr;

public class GeneralAccurateOCR {

    @Test
    public void txOCR() {
        // 识别结果保存目录
        String saveFilePath = "E:\\documents\\DCIM\\unfinished\\";

		// 待识别图片目录
        String fromPic = "E:\\documents\\DCIM\\unfinished\\test";
        File directory = new File(fromPic);

        if (!directory.isDirectory()) {
            return;
        }

        int maxLength = 7 * 1024 * 1024 - 1000;

        // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
        // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        Credential cred = new Credential("secretId", "secretKey");
        // 实例化一个http选项,可选的,没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");
        // 实例化一个client选项,可选的,没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化要请求产品的client对象,clientProfile是可选的
        OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);

        List<String> errFiles = new ArrayList<>();
        List<String> errInfo = new ArrayList<>();
        List<String> jsonInfo = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        List<String> wrongChars = new ArrayList<>();

        int paragraphNo = 0;

        int count = 1;
        for (File file : directory.listFiles()) {
            String base64 = GetImageStr(file.getAbsolutePath());
            if (base64.length() > maxLength) {
                errFiles.add(file.getAbsolutePath());
                continue;
            }

            try {
                // 实例化一个请求对象,每个接口都会对应一个request对象
                GeneralAccurateOCRRequest req = new GeneralAccurateOCRRequest();
                req.setImageBase64(base64);
                // 返回的resp是一个GeneralAccurateOCRResponse的实例,与请求对象对应
                GeneralAccurateOCRResponse resp = client.GeneralAccurateOCR(req);

                TextDetection[] detections = resp.getTextDetections();
                if (detections != null) {

                    for (TextDetection detection : detections) {
                        // 错别字
                        if (detection.getConfidence() < 90) {
                            wrongChars.add(detection.getDetectedText() + ":" + detection.getConfidence());
                        }

                        // 判断是否需要换行
                        if (StringUtils.isNotBlank(detection.getAdvancedInfo())) {
                            JSONObject jsonObject = JSONObject.parseObject(detection.getAdvancedInfo());
                            JSONObject parag = jsonObject.getJSONObject("Parag");
                            if (parag != null) {
                                int paragNo = parag.getIntValue("ParagNo");
                                if (paragraphNo != paragNo) {
                                    //增加回车符
                                    sb.append("\r\n");
                                    paragraphNo = paragNo;
                                }
                            }
                        }

                        sb.append(detection.getDetectedText());
                    }
                }

                jsonInfo.add(GeneralAccurateOCRResponse.toJsonString(resp));
            } catch (TencentCloudSDKException e) {
                errFiles.add(file.getAbsolutePath());
                errInfo.add(file + e.toString());
            }

            paragraphNo = 0;
            System.out.println(count++);
        }

        try {
            FileWriter fw = new FileWriter(saveFilePath +"content.txt", true);
            fw.write(sb.toString()+"\r\n");
            fw.close();

            fw = new FileWriter(saveFilePath +"failed.txt", true);
            fw.write(errFiles.toString()+"\r\n");
            fw.close();

            fw = new FileWriter(saveFilePath +"error.txt", true);
            fw.write(errInfo.toString()+"\r\n");
            fw.close();

            fw = new FileWriter(saveFilePath +"response.txt", true);
            fw.write(jsonInfo.toString()+"\r\n");
            fw.close();

            fw = new FileWriter(saveFilePath +"wrongChars.txt", true);
            fw.write(wrongChars.toString()+"\r\n");
            fw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(sb.toString());
        System.out.println();
        System.out.println();
        System.out.println("==================失败文件开始==================");
        System.out.println(errFiles);
        System.out.println("==================失败文件结束==================");
        System.out.println();
        System.out.println();
        System.out.println("==================异常信息开始==================");
        System.out.println(errInfo);
        System.out.println("==================异常信息结束==================");
        System.out.println();
        System.out.println();
        System.out.println("==================json返回结果开始==================");
        System.out.println(jsonInfo);
        System.out.println("==================json返回结果结束==================");
        System.out.println();
        System.out.println();
        System.out.println("==================错别字开始==================");
        System.out.println(wrongChars);
        System.out.println("==================错别字结束==================");

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值