本篇介绍的是基于百度人工智能接口的文字识别实现。
1. 注册百度云,获得AppID
此处百度云非百度云盘,而是百度智能云。
大家可进入https://cloud.baidu.com/ 自行注册,这里就不多说了。
接下来,我们进行应用的创建


所需接口根据实际勾选,我们暂时只需前四个即可。

2. 日常demo操作
pom.xml:
- <dependencies>
- <!-- 百度人工智能依赖 -->
- <!-- https://mvnrepository.com/artifact/com.baidu.aip/java-sdk -->
- <dependency>
- <groupId>com.baidu.aip</groupId>
- <artifactId>java-sdk</artifactId>
- <version>4.11.3</version>
- </dependency>
- <!-- 对象转换成json -->
- <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.8</version>
- </dependency>
- </dependencies>
JsonChange.class:(json处理工具类)
- public class JsonChange {
-
- /**
- * json字符串转换为map
- */
- public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
- return mapper.readValue(jsonString, Map.class);
- }
-
- }
OcrController.class:
AipOcr client = new AipOcr(“AppID”, “API Key”, “Secret Key”) 切记换成刚刚创建的应用的AppID,而且三个参数均是String类型。
- @RestController
- public class OcrController {
-
- @PostMapping(value = "/ocr")
- public Map<Object, Object> ocr(MultipartFile file) throws Exception {
- AipOcr client = new AipOcr("AppID", "API Key", "Secret Key");
- // 传入可选参数调用接口
- HashMap<String, String> options = new HashMap<String, String>(4);
- 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.basicGeneral(buf, options);
-
- Map map = JsonChange.json2map(res.toString());
- return map;
- }
-
- }
如果只想要识别出来的文字即可,可加入
- // 提取并打印出识别的文字
- List list = (List) map.get("words_result");
- int len = ((List) map.get("words_result")).size();
- for(int i=0; i<len; i++) {
- str = str + ((Map) list.get(i)).get("words") + "\n";
- }
接下来 postman 测试

ocr识别出的全部数据输出

提取其中识别的文字,剔除其他信息
源码下载
到此这篇关于SpringBoot+OCR 实现图片文字识别的文章就介绍到这了,更多相关SpringBoot OCR 图片文字识别内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!