七七鱼竞价托管,湖南专业的关键词优化,施工企业报验资质清单,业务型网站做seo一、开发背景 根据项目需求#xff0c;我们需要完成LED显示屏实时显示歌词的效果。最优的方法是调用歌曲播放器的API获取歌词#xff0c;但是由于这个开发资格不是很好申请#xff0c;因此我们采用其他方案#xff0c;即通过OCR识别获取歌词#xff0c;并投射到LED显示屏上…一、开发背景 根据项目需求我们需要完成LED显示屏实时显示歌词的效果。最优的方法是调用歌曲播放器的API获取歌词但是由于这个开发资格不是很好申请因此我们采用其他方案即通过OCR识别获取歌词并投射到LED显示屏上。本项目使用IDEA开发。 本文将跳过对歌词的截图以及后续将文本投射到LED显示屏的代码下文将主要介绍如何调用百度OCR文字识别的API接口并将识别的文本打印出来。
二、具体实现 首先登录百度开发者中心进行实名认证后创建应用程序。 API开发文档通用文字识别标准版 根据开发文档首先我们需要从本地读取图片并进行Base64编码与URLencode. // 读取图片文件为字节数组
File file new File(D:\\Led_Display\\screenshot.png);
byte[] imageBytes new byte[0];
try {imageBytes Files.readAllBytes(file.toPath());
} catch (IOException e) {throw new RuntimeException(e);
}
// 将字节数组转换为base64编码的字符串
String base64String Base64.getEncoder().encodeToString(imageBytes);
// 将base64编码的字符串进行urlencode
encodedStringnull;//清空
try {encodedString URLEncoder.encode(base64String, UTF-8);
} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);
}
// 打印结果
System.out.println(Base64编码后图片:encodedString); 在JAVA中我们需要先创建一个HttpClient对象和HttpRequest对象这将用于封装和发送请求并在request对象中带入上面编码的图片信息。
request HttpRequest.newBuilder()// 设置请求的URL其中access_token是通过API Key和Secret Key获取的.uri(URI.create(https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token???))// 设置请求的HeaderContent-Type为application/x-www-form-urlencoded.header(Content-Type, application/x-www-form-urlencoded)// 设置请求的Bodyimage参数为encodedString.POST(HttpRequest.BodyPublishers.ofString(image encodedString)).build(); 发送请求并获取HttpResponse对象此处我们需要捕捉异常。
// 发送HttpPost对象并获取HttpResponse对象
HttpResponseString response null;
try {response httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {throw new RuntimeException(e);
} catch (InterruptedException e) {throw new RuntimeException(e);
} 根据开发文档获取返回状态码等信息并提取出我们需要的信息打印输出。 // 获取响应状态码
int statusCode response.statusCode();
// 获取响应体内容
String body response.body();
// 打印结果
System.out.println(请求状态编码: statusCode);
System.out.println(响应Body: body);
if(statusCode!200)return ;
else
{JsonParser jsonParsernew JsonParser();JsonObject jsonObject (JsonObject) jsonParser.parse(body);JsonArray words_result jsonObject.getAsJsonArray(words_result);if(words_result.size()1) {JsonObject json (JsonObject) jsonParser.parse(words_result.get(0).toString());System.out.println(解析到的文本为: json.get(words).toString());System.out.println(OCR功能测试正常);return json.get(words).toString();}else {System.out.println(OCR未识别到任何文本);return ;}
}
三、运行测试 打开音乐播放器查看运行效果。 不难看到我们已经成功识别了相关文本下一步只需要调用LED显示屏的开发文档将文字发送到显示屏即可。 注意上述代码中的APIToken应该动态获取本文未提及具体可查看鉴权认证机制