一、開發(fā)背景
? ? ? ? 根據(jù)項目需求,我們需要完成LED顯示屏實時顯示歌詞的效果。最優(yōu)的方法是調用歌曲播放器的API獲取歌詞,但是由于這個開發(fā)資格不是很好申請,因此我們采用其他方案,即通過OCR識別獲取歌詞,并投射到LED顯示屏上。本項目使用IDEA開發(fā)。
? ? ? ? 本文將跳過對歌詞的截圖以及后續(xù)將文本投射到LED顯示屏的代碼,下文將主要介紹如何調用百度OCR文字識別的API接口,并將識別的文本打印出來。
二、具體實現(xiàn)
? ? ? ? 首先,登錄百度開發(fā)者中心,進行實名認證后,創(chuàng)建應用程序。
? ? ? ? API開發(fā)文檔:通用文字識別(標準版)
? ? ? ? 根據(jù)開發(fā)文檔,首先我們需要從本地讀取圖片,并進行Base64編碼與URLencode.
// 讀取圖片文件為字節(jié)數(shù)組
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);
}
// 將字節(jié)數(shù)組轉換為base64編碼的字符串
String base64String = Base64.getEncoder().encodeToString(imageBytes);
// 將base64編碼的字符串進行urlencode
encodedString=null;//清空
try {
encodedString = URLEncoder.encode(base64String, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// 打印結果
System.out.println("Base64編碼后圖片:"+encodedString);
? ? ? ? 在JAVA中,我們需要先創(chuàng)建一個HttpClient對象和HttpRequest對象,這將用于封裝和發(fā)送請求,并在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=???"))
// 設置請求的Header,Content-Type為application/x-www-form-urlencoded
.header("Content-Type", "application/x-www-form-urlencoded")
// 設置請求的Body,image參數(shù)為encodedString
.POST(HttpRequest.BodyPublishers.ofString("image=" + encodedString))
.build();
? ? ? ? 發(fā)送請求,并獲取HttpResponse對象,此處我們需要捕捉異常。
// 發(fā)送HttpPost對象,并獲取HttpResponse對象
HttpResponse<String> response = null;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
? ? ? ? 根據(jù)開發(fā)文檔,獲取返回狀態(tài)碼等信息,并提取出我們需要的信息打印輸出。
// 獲取響應狀態(tài)碼
int statusCode = response.statusCode();
// 獲取響應體內容
String body = response.body();
// 打印結果
System.out.println("請求狀態(tài)編碼: " + statusCode);
System.out.println("響應Body: " + body);
if(statusCode!=200)
return "";
else
{
JsonParser jsonParser=new 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 "";
}
}
三、運行測試
? ? ? ? 打開音樂播放器,查看運行效果。
? ? ? ? 不難看到,我們已經(jīng)成功識別了相關文本,下一步只需要調用LED顯示屏的開發(fā)文檔將文字發(fā)送到顯示屏即可。文章來源:http://www.zghlxwxcb.cn/news/detail-741996.html
? ? ? ? 注意,上述代碼中的APIToken應該動態(tài)獲取,本文未提及,具體可查看:鑒權認證機制文章來源地址http://www.zghlxwxcb.cn/news/detail-741996.html
到了這里,關于百度OCR識別圖片文本字符串——物聯(lián)網(wǎng)上位機軟件的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!