【SpringBoot】整合百度文字识别

server/2024/9/24 0:17:41/

流程图

一、前期准备

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文件

java"># 这是一个配置块,用于设置百度OCR服务的认证信息。
baidu:ocr: # OCR服务的配置项appId:  # 百度OCR服务的应用IDapiKey:  # 百度OCR服务的API密钥secretKey:  # 百度OCR服务的密钥spring:thymeleaf:cache: false

2.3 eneity层

java">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 IDprivate String appId;// 百度OCR的API Keyprivate String apiKey;// 百度OCR的Secret Keyprivate String secretKey;
}

2.5 控制器

java">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对象@Autowiredpublic 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 TokenString 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>

三、效果展示


http://www.ppmy.cn/server/45164.html

相关文章

内存函数<C语言>

前言 前面两篇文章介绍了字符串函数&#xff0c;不过它们都只能用来处理字符串&#xff0c;C语言中也内置了一些内存函数来对不同类型的数据进行处理&#xff0c;本文将介绍&#xff1a;memcpy()使用以及模拟实现&#xff0c;memmove()使用以及模拟实现&#xff0c;memset()使用…

如何配置才能连接远程服务器上的 redis server ?

文章目录 Intro修改点 Intro 以阿里云服为例。 首先&#xff0c;我在我买的阿里云服务器中以下载源码、手动编译的方式安装了 redis-server&#xff0c;操作流程见&#xff1a;Ubuntu redis 下载解压配置使用及密码管理 && 包管理工具联网安装。 接着&#xff0c;我…

机器学习之二分类提升决策树(Two-class Boosted Decision Tree)

二分类提升决策树(Two-class Boosted Decision Tree)是一种常用的机器学习方法,主要用于分类任务。该方法结合了决策树模型和提升(boosting)算法的优点,通过多个弱分类器(通常是简单的决策树)来构建一个强分类器。下面是关于二分类提升决策树的主要概念和工作流程: 1…

关于《Java并发编程之线程池十八问》的补充内容

一、写在开头 在上一篇文章我们写《Java并发编程之线程池十八问》的时候,鉴于当时的篇幅已经过长,很多内容就没有扩展了,在这篇文章里对一些关键知识点进行对比补充。 二、Runnable vs Callable 在创建线程的时候,一般会选用 Runnable 和 Callable 两种方式。 【源码对…

最长递增子序列,交错字符串

第一题&#xff1a; 代码如下&#xff1a; int lengthOfLIS(vector<int>& nums) {//dp[i]表示以第i个元素为结尾的最长子序列的长度int n nums.size();int res 1;vector<int> dp(n, 1);for (int i 1; i < n; i){for (int j 0; j < i; j){if (nums[i]…

Kubectl 的使用——k8s陈述式资源管理

一、kebuctl简介: kubectl 是官方的CLI命令行工具&#xff0c;用于与 apiserver 进行通信&#xff0c;将用户在命令行输入的命令&#xff0c;组织并转化为 apiserver 能识别的信息&#xff0c;进而实现管理 k8s 各种资源的一种有效途径。 对资源的增、删、查操作比较方便&…

长安链使用Golang编写智能合约教程(一)

长安链是分2.1.和2.3.两个版本&#xff0c;本节面说的是2.1.的版本 需要2.3.版本的合约&#xff0c;请看教程&#xff08;二&#xff09;&#xff01; 教程&#xff08;二&#xff09;我会写如何查历史数据 教程二&#xff1a;&#xff08;长安链2.3.的版本的智能合约编写&…

代码随想录算法训练营第22天(py)| 二叉树 | 669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树

669. 修剪二叉搜索树 力扣链接 给定一个二叉搜索树&#xff0c;同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树&#xff0c;使得所有节点的值在[L, R]中 (R>L) 思路 如果当前节点元素小于low&#xff0c;递归右子树&#xff0c;返回符合条件的头节点 如果当前节点元…