最近项目中要使用到OCR功能,发现百度AI开放平台这部分能力比较强,于是注册账号并调用相关API。
先在开放平台注册完毕,并创建一个应用,得到AppID, API Key, Secret Key等参数。
等上述准备工作就绪,开始测试OCR相关的功能模块。
首先在pom.xml文件中增加依赖。
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.13</version>
</dependency>
然后开始调用API
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import org.json.JSONArray;
import org.json.JSONObject;
import com.baidu.aip.ocr.AipOcr;
public class BdImagUtil {
public static final String APP_ID = "xxx";
public static final String API_KEY = "xxx";
public static final String SECRET_KEY = "xxx";
public static void image2text() throws Exception{
byte[] imageBytes = readImage();
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
JSONObject response = client.basicGeneral(imageBytes, new HashMap<String, String>());
System.out.println("response is: \n" + response);
JSONArray jsonArray = response.getJSONArray("words_result");
System.out.println(jsonArray.toString());
}
public static byte[] readImage() throws Exception {
InputStream ins = BdImagUtil.class.getClassLoader().getResourceAsStream("11.jpg");
byte[] bytes = new byte[ins.available()];
ins.read(bytes);
ins.close();
return bytes;
}
public static void main(String[] args) throws Exception {
image2text();
}
}
结果代码初始输出为:
response is:
{"error_msg":Open api qps result limit reached","error code":18}
上面的错误提示显示是qps调用超出了上限,但是很明显,我们就一个java代码,应该不存在说qps太大超过上限的问题。
经过搜索发现,是我们在创建应用的时候,还需要主动去领取免费的额度!
如上图,有个领取免费资源的按钮,点击该按钮领取即可。