百度OCR文字识别API使用心得 com.baidu.ocr.sdk.exception.SDKError[283604]
百度OCR文字識別API使用心得 com.baidu.ocr.sdk.exception.SDKError[283604]
本文轉載自好基友upuptop:https://blog.csdn.net/pyfysf/article/details/77455330
效果圖:
如下為文章正文:
最近有個小項目使用到了OCR技術,順便到網上搜索了一下,大家都在使用百度的API,所以我就調用了百度的接口。
在使用的過程中也是遇到了各種各樣的錯誤,比如 TOKEN ERROR 了等等。
一、注冊登錄百度云平臺
首先注冊登陸百度賬號,點擊這里跳轉到百度API接口首頁:
https://login.bce.baidu.com/?account=&redirect=http%3A%2F%2Fconsole.bce.baidu.com%2F
注冊登陸之后在左側的 "產品服務" 找到 “文字識別”:
創 "文字識別" 建項目:
創建項目后,在應用類表獲取項目的:API Key、Secret Key
粘貼到項目 Demo 中:
二、配置SDK,查看文檔調用接口
文檔地址:https://cloud.baidu.com/doc/OCR/OCR-Android-SDK.html#.E6.95.B0.E6.8D.AE.E6.8E.A5.E5.8F.A3
博主使用的是Android平臺的SDK,根據步驟進行SDK工程配置。
配置完工程之后博主就很驚喜的去調用方法進行寫代碼了。
但是,logcat總是報錯。說獲取token失敗,packname錯誤或者AK和SK錯誤。
這里我就很是納悶,我根本沒有設置項目的包名,并且我的AK和SK是正確的。大家有知道解決方法,求大神在評論區指教博主,博主在這里叩謝。
然后經過我查詢資料,我選擇請求API,從而不去調用百度封裝的方法。
三、實現代碼片段(不提供xml布局文件)
下面將貼一些代碼片段。不想看代碼片段的直接下滑到最后下載 Demo 源碼。
博主是打開相機拍一張照片進行掃描實現OCR識別文字,百度的API可以接受本地圖片的路徑,或者網絡上的圖片URL也可以進行OCR文字掃描。
我用到了百度提供的UI,在SDK里面導入到項目里面就可以了。
/**?*?打開相機
?*/
public?void?openCameraByBaidu()?{
????Intent?intent?=?new?Intent(GuideActivity.this,?CameraActivity.class);
????intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
????????????FileUtil.getSaveFile(getApplication()).getAbsolutePath());
????intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
????????????CameraActivity.CONTENT_TYPE_GENERAL);
????startActivityForResult(intent,?OPEN_CAMERA_OK);
}
拍照之后獲取照片的保存路徑:
@Overrideprotected?void?onActivityResult(int?requestCode,?int?resultCode,?Intent?data)?{
????
????if?(requestCode?==?OPEN_CAMERA_OK?&&?resultCode?==?RESULT_OK)?{
????????String?photoPath?=?FileUtil.getSaveFile(this).getAbsolutePath();
????????checkData(photoPath);
????}
}
核心代碼在這里!!
請求百度文字識別API,進行圖片OCR識別,我用的是 xUtils3.0 請求的網絡。也可以使用HTTPConnection 發起 get 請求,如下是參考代碼:
?/**?*?請求百度API接口,進行獲取數據
?*
?*?@param?filePath
?*/
private?void?checkData(String?filePath)?{
????try?{
????????
????????byte[]?imgData?=?FileUtil.readFileByBytes(filePath);
????????
????????String?imgStr?=?Base64Util.encode(imgData);
????????final?String?params?=?URLEncoder.encode("image",?"UTF-8")?+?"="?+?URLEncoder.encode(imgStr,?"UTF-8");
????????RequestParams?entiry?=?new?RequestParams(ConstantValue.BAIDU_TOKEN_URL);
????????x.http().get(entiry,?new?Callback.CommonCallback<String>()?{
????????????@Override
????????????public?void?onSuccess(final?String?result)?{
????????????????Gson?gson?=?new?Gson();
????????????????TokenInfo?tokenInfo?=?gson.fromJson(result,?TokenInfo.class);
????????????????final?String?access_token?=?tokenInfo.getAccess_token();
????????????????new?Thread()?{
????????????????????public?void?run()?{
????????????????????????public?static?final?String?BAIDU_TOKEN_URL
????????????????????????????????=?"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="?+?你在百度控制臺創建的AK+?"&client_secret="?+
????????????????????????????????你在百度控制臺創建的SK;
????????????????????????String?resultStr?=?HttpUtil.post(ConstantValue.BAIDU_INTER_URL,?access_token,?params);
????????????????????????Log.e("MainActivity",?"MainActivity?onSuccess()"?+?resultStr);
????????????????????????Message?msg?=?Message.obtain();
????????????????????????msg.obj?=?resultStr;
????????????????????????msg.what?=?PRESER_IMG_OK;
????????????????????????handler.sendMessage(msg);
????????????????????}
????????????????}.start();
????????????}
????????????@Override
????????????public?void?onError(Throwable?ex,?boolean?isOnCallback)?{
????????????}
????????????@Override
????????????public?void?onCancelled(CancelledException?cex)?{
????????????}
????????????@Override
????????????public?void?onFinished()?{
????????????}
????????});
????}?catch?(UnsupportedEncodingException?e)?{
????????e.printStackTrace();
????}?catch?(IOException?e)?{
????????e.printStackTrace();
????}
}
解析數據,官方返回的是一個json串。所以我們進行解析數據
private?static?Handler?handler?=?new?Handler()?{????public?void?handleMessage(Message?msg)?{
????????switch?(msg.what)?{
????????????case?PRESER_IMG_OK:
????????????????String?data?=?(String)?msg.obj;
????????????????preserData(data);
????????????????break;
????????}
????}
};
private?static?void?preserData(String?data)?{
????Gson?gson?=?new?Gson();
????WordInfo?wordInfo?=?gson.fromJson(data,?WordInfo.class);
????if(wordInfo.getError_code()?!=?null)?{
????????if?(wordInfo.getError_code()?==?17?||?wordInfo.getError_code()?==?19?||?wordInfo.getError_code()?==?18)?{
????????????Toast.makeText(MyApp.getContext(),?"請求量超出限額",?Toast.LENGTH_SHORT).show();
????????????return;
????????}
????}
????if?(wordInfo.getWords_result()?==?null?||?wordInfo.getWords_result_num()?<?0?||?wordInfo.getWords_result().size()?==?0)?{
????????Toast.makeText(MyApp.getContext(),?"文字掃描識別失敗,請重試",?Toast.LENGTH_SHORT).show();
????????return;
????}
????wordInfo.getWords_result()?;//這里面就是掃描出來的數據
}
FileUtil
public?static?File?getSaveFile(Context?context)?{????????File?file?=?new?File(context.getFilesDir(),?"pic.jpg");
????????return?file;
????}
????/**
?????*?根據文件路徑讀取byte[]?數組
?????*/
????public?static?byte[]?readFileByBytes(String?filePath)?throws?IOException?{
????????File?file?=?new?File(filePath);
????????if?(!file.exists())?{
????????????throw?new?FileNotFoundException(filePath);
????????}?else?{
????????????ByteArrayOutputStream?bos?=?new?ByteArrayOutputStream((int)?file.length());
????????????BufferedInputStream?in?=?null;
????????????try?{
????????????????in?=?new?BufferedInputStream(new?FileInputStream(file));
????????????????short?bufSize?=?1024;
????????????????byte[]?buffer?=?new?byte[bufSize];
????????????????int?len1;
????????????????while?(-1?!=?(len1?=?in.read(buffer,?0,?bufSize)))?{
????????????????????bos.write(buffer,?0,?len1);
????????????????}
????????????????byte[]?var7?=?bos.toByteArray();
????????????????return?var7;
????????????}?finally?{
????????????????try?{
????????????????????if?(in?!=?null)?{
????????????????????????in.close();
????????????????????}
????????????????}?catch?(IOException?var14)?{
????????????????????var14.printStackTrace();
????????????????}
????????????????bos.close();
????????????}
????????}
????}
}
HttpUtils
/**?*?http?工具類
?*/
public?class?HttpUtil?{
????public?static?String?post(String?requestUrl,?String?accessToken,?String?params)??{
????????try?{
????????????String?generalUrl?=?requestUrl?+?"?access_token="?+?accessToken;
????????????URL?url?=?new?URL(generalUrl);
????????????//?打開和URL之間的連接
????????????HttpURLConnection?connection?=?(HttpURLConnection)?url.openConnection();
????????????connection.setRequestMethod("POST");
????????????//?設置通用的請求屬性
????????????connection.setRequestProperty("Content-Type",?"application/x-www-form-urlencoded");
????????????connection.setRequestProperty("Connection",?"Keep-Alive");
????????????connection.setUseCaches(false);
????????????connection.setDoOutput(true);
????????????connection.setDoInput(true);
????????????//?得到請求的輸出流對象
????????????DataOutputStream?out?=?new?DataOutputStream(connection.getOutputStream());
????????????out.writeBytes(params);
????????????out.flush();
????????????out.close();
????????????//?建立實際的連接
????????????connection.connect();
????????????//?獲取所有響應頭字段
????????????Map<String,?List<String>>?headers?=?connection.getHeaderFields();
????????????//?遍歷所有的響應頭字段
????????????for?(String?key?:?headers.keySet())?{
????????????????System.out.println(key?+?"--->"?+?headers.get(key));
????????????}
????????????//?定義?BufferedReader輸入流來讀取URL的響應
????????????BufferedReader?in?=?null;
????????????if?(requestUrl.contains("nlp"))
????????????????in?=?new?BufferedReader(new?InputStreamReader(connection.getInputStream(),?"GBK"));
????????????else
????????????????in?=?new?BufferedReader(new?InputStreamReader(connection.getInputStream(),?"UTF-8"));
????????????String?result?=?"";
????????????String?getLine;
????????????while?((getLine?=?in.readLine())?!=?null)?{
????????????????result?+=?getLine;
????????????}
????????????in.close();
????????????System.out.println("result:"?+?result);
????????????return?result;
????????}catch?(Exception?e){
????????????throw?new?RuntimeException(e);
????????}
????}
}
Base64Util
/**?*?Base64?工具類
?*/
public?class?Base64Util?{
????private?static?final?char?last2byte?=?(char)?Integer.parseInt("00000011",?2);
????private?static?final?char?last4byte?=?(char)?Integer.parseInt("00001111",?2);
????private?static?final?char?last6byte?=?(char)?Integer.parseInt("00111111",?2);
????private?static?final?char?lead6byte?=?(char)?Integer.parseInt("11111100",?2);
????private?static?final?char?lead4byte?=?(char)?Integer.parseInt("11110000",?2);
????private?static?final?char?lead2byte?=?(char)?Integer.parseInt("11000000",?2);
????private?static?final?char[]?encodeTable?=?new?char[]{'A',?'B',?'C',?'D',?'E',?'F',?'G',?'H',?'I',?'J',?'K',?'L',?'M',?'N',?'O',?'P',?'Q',?'R',?'S',?'T',?'U',?'V',?'W',?'X',?'Y',?'Z',?'a',?'b',?'c',?'d',?'e',?'f',?'g',?'h',?'i',?'j',?'k',?'l',?'m',?'n',?'o',?'p',?'q',?'r',?'s',?'t',?'u',?'v',?'w',?'x',?'y',?'z',?'0',?'1',?'2',?'3',?'4',?'5',?'6',?'7',?'8',?'9',?'+',?'/'};
????public?Base64Util()?{
????}
????public?static?String?encode(byte[]?from)?{
????????StringBuilder?to?=?new?StringBuilder((int)?((double)?from.length?*?1.34D)?+?3);
????????int?num?=?0;
????????char?currentByte?=?0;
????????int?i;
????????for?(i?=?0;?i?<?from.length;?++i)?{
????????????for?(num?%=?8;?num?<?8;?num?+=?6)?{
????????????????switch?(num)?{
????????????????????case?0:
????????????????????????currentByte?=?(char)?(from[i]?&?lead6byte);
????????????????????????currentByte?=?(char)?(currentByte?>>>?2);
????????????????????case?1:
????????????????????case?3:
????????????????????case?5:
????????????????????default:
????????????????????????break;
????????????????????case?2:
????????????????????????currentByte?=?(char)?(from[i]?&?last6byte);
????????????????????????break;
????????????????????case?4:
????????????????????????currentByte?=?(char)?(from[i]?&?last4byte);
????????????????????????currentByte?=?(char)?(currentByte?<<?2);
????????????????????????if?(i?+?1?<?from.length)?{
????????????????????????????currentByte?=?(char)?(currentByte?|?(from[i?+?1]?&?lead2byte)?>>>?6);
????????????????????????}
????????????????????????break;
????????????????????case?6:
????????????????????????currentByte?=?(char)?(from[i]?&?last2byte);
????????????????????????currentByte?=?(char)?(currentByte?<<?4);
????????????????????????if?(i?+?1?<?from.length)?{
????????????????????????????currentByte?=?(char)?(currentByte?|?(from[i?+?1]?&?lead4byte)?>>>?4);
????????????????????????}
????????????????}
????????????????to.append(encodeTable[currentByte]);
????????????}
????????}
????????if?(to.length()?%?4?!=?0)?{
????????????for?(i?=?4?-?to.length()?%?4;?i?>?0;?--i)?{
????????????????to.append("=");
????????????}
????????}
????????return?to.toString();
????}
}
這樣就可以實現了。
本文的案例源碼下載地址在這里哦!!!!
https://download.csdn.net/download/pyfysf/10406761
有問題可以加博主QQ哦。337081267
如果文章有錯的地方歡迎指正,大家互相留言交流。習慣在微信看技術文章,想要獲取更多的Java資源的同學,可以關注微信公眾號:niceyoo
posted @ 2019-05-16 16:17 niceyoo 閱讀(...) 評論(...) 編輯 收藏總結
以上是生活随笔為你收集整理的百度OCR文字识别API使用心得 com.baidu.ocr.sdk.exception.SDKError[283604]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 极域电子教室破解!
- 下一篇: Hadoop的多节点集群启动,唯独没有n