【SpringBoot】整合百度文字识别

流程图

一、前期准备

1.1 打开百度智能云官网找到管理中心创建应用

全选文字识别

1.2 保存好AppId、API Key和Secret Key

1.3 找到通用场景文字识别,立即使用

1.4 根据自己需要,选择要开通的项目

二、代码编写

以通用文字识别(高精度版)为例

2.1 加依赖(pom.xml)

    <dependencies>

        <!-- 引入Spring Boot的web starter依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 引入Lombok依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 引入Spring Boot的测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 百度人工智能依赖 -->
        <dependency>
            <groupId>com.baidu.aip</groupId>
            <artifactId>java-sdk</artifactId>
            <version>4.11.3</version>
        </dependency>

        <!-- okhttp -->
        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.12.0</version>
        </dependency>

        <!-- 对象转换成json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>

        <!-- thymeleaf模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

2.2 编写yml文件

# 这是一个配置块,用于设置百度OCR服务的认证信息。
baidu:
  ocr: # OCR服务的配置项
    appId:  # 百度OCR服务的应用ID
    apiKey:  # 百度OCR服务的API密钥
    secretKey:  # 百度OCR服务的密钥

spring:
  thymeleaf:
    cache: false

2.3 eneity层

package com.baiduocr.entity;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * BaiduOcrProperties类用于配置百度OCR服务的相关属性。
 * 该类通过@ConfigurationProperties注解与配置文件中的baidu.ocr前缀绑定,
 * 使得我们可以从配置文件中动态读取appId, apiKey和secretKey等属性值
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "baidu.ocr")
public class BaiduOcrProperties {
    // 百度OCR的App ID
    private String appId;
    // 百度OCR的API Key
    private String apiKey;
    // 百度OCR的Secret Key
    private String secretKey;
}

2.5 控制器

package com.baiduocr.controller;

import com.baidu.aip.ocr.AipOcr;
import com.baiduocr.entity.BaiduOcrProperties;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.*;

/**
 * OcrController类负责处理OCR相关的请求。
 * 它利用百度OCR服务对上传的文件或文本进行识别,并返回识别结果。
 */

@Controller
public class OcrController {
    // 注入BaiduOcrProperties对象,用于获取百度OCR服务的配置信息
    private final BaiduOcrProperties baiduOcrProperties;
    // 创建一个OkHttpClient对象,用于发送HTTP请求到百度OCR服务
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    // 构造函数,注入BaiduOcrProperties对象,用于初始化BaiduOcrProperties对象
    @Autowired
    public OcrController(BaiduOcrProperties baiduOcrProperties) {
        this.baiduOcrProperties = baiduOcrProperties;
    }

    @RequestMapping(value = {"/", "/ocr"})
    public String index() {
        return "ocr";
    }
    /**
     * 处理OCR识别请求。
     *
     * @param file 用户上传的文件,将进行OCR识别。
     * @param model Spring模型,用于在识别后向视图传递数据。
     * @return 视图名称,根据识别结果决定是显示结果还是错误页面。
     */
    @RequestMapping(value = "/doOcr")
    public String ocr(MultipartFile file, Model model) {
        try {
            List<String> ocrResult = performOcr(file); // 执行OCR识别
            model.addAttribute("ocrResult", ocrResult); // 将识别结果添加到模型中
        } catch (Exception e) {
            return "error"; // 识别失败,返回错误页面
        }
        return "ocr_result"; // 识别成功,返回结果页面
    }

    /**
     * 执行OCR识别操作。
     *
     * @param file 需要进行OCR识别的文件。
     * @return 识别到的文本列表。
     * @throws Exception 如果识别过程中出现错误,则抛出异常。
     */
    private List<String> performOcr(MultipartFile file) throws Exception {
        AipOcr client = new AipOcr(baiduOcrProperties.getAppId(), baiduOcrProperties.getApiKey(), baiduOcrProperties.getSecretKey()); // 创建百度OCR客户端

        // 获取Access Token
        String accessToken = getAccessToken();

        HashMap<String, String> options = new HashMap<>(); // 设置OCR识别的选项
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        byte[] buf = file.getBytes(); // 从文件中读取内容
        JSONObject res = client.basicAccurateGeneral(buf, options);  // 使用高精度接口进行通用文字识别

        List<String> wordsList = new ArrayList<>(); // 存储识别出的文本
        for (Object obj : res.getJSONArray("words_result")) { // 遍历识别结果,提取文本
            JSONObject jsonObj = (JSONObject) obj;
            wordsList.add(jsonObj.getString("words"));
        }
        return wordsList;
    }

    /**
     * 从百度OCR服务获取Access Token。
     *
     * @return Access Token,用于身份验证。
     * @throws IOException 如果在获取Access Token过程中出现IO错误。
     */
    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + baiduOcrProperties.getApiKey()
                + "&client_secret=" + baiduOcrProperties.getSecretKey());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute(); // 发送请求,获取响应
        return new JSONObject(response.body().string()).getString("access_token"); // 从响应中提取Access Token
    }


}

2.6 前端页面(thymeleaf)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>OCR识别</title>
</head>
<body>

<h1>上传图片进行OCR识别</h1>
<form th:action="@{/doOcr}" method="post" enctype="multipart/form-data">
    <input type="file" name="file" accept="image/*">
    <button type="submit">上传并识别</button>
</form>

</body>
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: #f8f9fa;
    }
    h1 {
        color: #343a40;
        margin-top: 20px;
    }
    form {
        margin: 20px 0;
        padding: 20px;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        background-color: #fff;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    input[type="file"] {
        margin-bottom: 10px;
    }
    button {
        background-color: #007bff;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
    button:hover {
        background-color: #0056b3;
    }
</style>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>OCR结果</title>
</head>
<body>

<h1>OCR识别结果</h1>
<div th:if="${ocrResult != null}">
    <ul>
        <li th:each="word : ${ocrResult}" th:text="${word}"></li>
    </ul>
</div>
<a href="/">返回首页</a>

</body>
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: #f8f9fa;
    }
    h1 {
        color: #343a40;
        margin-top: 20px;
    }
    div {
        margin: 20px 0;
        padding: 20px;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        background-color: #fff;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        width: 80%;
        max-width: 800px;
    }
    ul {
        list-style-type: none;
        padding: 0;
    }
    li {
        padding: 5px 0;
        border-bottom: 1px solid #dee2e6;
    }
    a {
        margin-top: 20px;
        color: #007bff;
        text-decoration: none;
    }
    a:hover {
        text-decoration: underline;
    }
</style>
</html>

三、效果展示

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
计算机视觉(Computer Vision)又称为机器视觉(Machine Vision),顾名思义是一门“教”会计算机如何去“看”世界的学科。在机器学习大热的前景之下,计算机视觉与自然语言处理(Natural Language Process, NLP)及语音识别(Speech Recognition)并列为机器学习方向的三大热点方向。在如今互联网时代,人工智能发展迅速,计算机视觉领域应用非常广泛,对人才的需求也是非常大,计算机视觉在IT领域的工资水平非常高,初级就能达到一个很好的薪资水平,学好计算机视觉,势在必得,增加自己的竞争力以及给自己一个好的薪水。 以下是计算机视觉部分应用场景,可以看到它的需求非常大:1.Google, MS, Facebook, Apple,华为,阿里,腾讯,百度等世界科技公司,无一没有建立自己的AI实验室,AI里面,计算机视觉或图像处理是非常重要的一块,当然它们研究方向就多了,几乎会涵盖所有方向。2.世界各大汽车公司,如特斯拉,宝马。汽车公司开始发力自动驾驶,而自动驾驶里面最核心的技术就是“教”汽车里的电脑如何通过摄像头实时产生的图片和视频自动驾驶。因此视觉和图像处理便是核心技术所在,如行人探测,道路识别,模式识别。3.Adobe,美图秀秀等照片、winrar、real player等视频处理、压缩软件。这个不多说,直观的应用,比如降噪,图像分割、图像压缩、视频压缩。4.AR(增强现实)最近由于Pockman GO的风靡全球又被推到第一线,而Google Class或者三星Gear眼镜等等,也无不和图像处理、计算机视觉的科研有关。预测这将是未来几年主推的东西。5.迪士尼等各大电影制片公司。3-D电影,以及各种炫酷的电影特效,当然里面不光有图像处理,还有计算机图形学的东西在里面。6.地平线,大疆无人机等机器人公司。和自动驾驶一个道理,机器人要通过摄像头“判断”并躲开前方障碍物,核心技术都在视觉和图像处理。7.医疗器械设备公司。医学图像处理,核磁共振,断层扫描等等,众所周知医疗行业都是暴利阿。8.工业级摄像头;包括高速路上的摄像头,机场火车站安检摄像头,工业流水线上的摄像头,嵌入了人脸或次品识别的芯片,智能地识别罪犯、次品,等等。 基于SpringBoot+Python多语言文档扫描处理和OCR识别系统,将以基础知识为根基,带大家完成一个强大的文档扫描处理和OCR识别系统,该系统将包含算法部分,算法服务,算法商业化api部分等。应用场景可以为:爬虫图片文字识别、文档图片自动整理和输出文字、实时扫描输出系统、PDF文档转换系统等等,算法可以商业化,系统同时实现了商业化api功能,商业价值非常高,大家可以基于课程项目的基础上进一步完善,做到商用,学到知识的同时,给自己额外增加收入。 本课程包含的技术: 开发工具为:IDEA、WebStorm、PyCharmPythonAnconaOpencvDjangoSpringBootSpringCouldVue+ElementUI+NODEJS等等 课程亮点: 1.与企业接轨、真实工业界产品2.强大的计算机视觉库OPENCV3.从基础到案例,逐层深入,学完即用4.市场主流的前后端分离架构和人工智能应用结开发5.多语言结开发,满足多元化的需求6.商业化算法api实现7.多Python环境切换8.微服务SpringBoot9.集成SpringCloud实现统一整方案 10.全程代码实操,提供全部代码和资料 11.提供答疑和提供企业技术方案咨询

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值