使用百度智能云文字识别API的前提是,在百度智能云中创建文字识别应用。
创建成功后我们能获取该应用的 APP_ID、API_Key、Secret_Key
python部分
1.获取授权的access_token
import requests
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=PcPyC85uM6bcAbCbfMGvCvg3&client_secret=OyItsZFYxBb0GAMsO6Zp1FN3rIQn2zUS'
response = requests.get(host)
if response:
print(response.json())
2.进行本地图片的识别
import requests
import base64
import ssl,sys
#使用 通用文字识别
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
#url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general' 高精度文字识别
data = {}
data['access_token']='24.2289cc8cff01bb58216efc99016fc9d9.3592000.1575883789.282335-17732285'
#读取图片
file=open('D:/test.png','rb')
image= file.read()
file.close()
data['image'] = base64.b64encode(image)
headers={
"Content-Type":"application/x-www-form-urlencoded",
"apikey":"PcPyC85uM6bcAbCbfMGvCvg2"
}
res = requests.post(url=url,headers=headers,data=data)
result = res.json()
# print(result)
# 将图中所以文字输出
print(result['words_result'])
for word in result['words_result']:
print(word['words'])
java部分
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
@CrossOrigin
@ResponseBody
@RestController
@RequestMapping("/api/orc")
public class OrcController {
@Value("${ORC_PATH}")
private String ORCPATH;
public static final String APP_ID = "17732275";
public static final String API_KEY = "PcPyC85uM6bcAbCbfMGvDvg2";
public static final String SECRET_KEY = "OyItsZFYxBb0GAMsO6Zp1FN3rIQn2zCS";
private AipOcr client;
public OrcController(){
client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);//类构造时,创建一个AipOcr单例
}
@RequestMapping(value = "/img/upload",method = RequestMethod.POST)
public String[] ImgUpload(@RequestParam("files") MultipartFile[] files,
HttpServletRequest request){
String[] result = new String[files.length];
int c=0;
for(MultipartFile file:files){
File desFile = new File(ORCPATH+"/"+file.getOriginalFilename());
if(!desFile.getParentFile().exists()){
desFile.getParentFile().mkdirs(); //创建父级文件路径
}
try {
file.transferTo(desFile);
}catch (IllegalStateException | IOException e){
e.printStackTrace();
}
JSONObject res = client.basicGeneral(desFile.getAbsolutePath(), new HashMap<String, String>());
try {
//解析通用文字识别返回的数据
JSONArray words_result = res.getJSONArray("words_result");
String words ="";
for (int i = 0; i < words_result.length(); i++) {
JSONObject jo = words_result.getJSONObject(i);
words += jo.getString("words");
}
result[c]=words;
} catch (JSONException e) {
e.printStackTrace();
}
c++;
}
return result;
}
}