Java-基于百度API的圖片文字識別(支持中文,英文和中英文混合)

使用之前需要獲取對應的項目API_KEY,SECRET_KEY,這些參數在使用API的時候必須用到,用于生成access_token。

如何獲取這些參數:在百度開發者中心申請一個“通用文字識別”項目,然后就可以獲取到這些參數。

準備條件都完成了,現在開始進行圖像識別了。

test4j圖片文字識別教程:http://blog.csdn.net/wsk1103/article/details/54173282

1. 準備pom文件

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.46</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.5.5</version>

</dependency>

1

2

3

4

5

6

7

8

9

10

11

12

2. 獲取access_token

package com.wsk.netty.check;

import org.json.JSONObject;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.List;

import java.util.Map;

/**

* 獲取token類

*

* @Author : WuShukai

* @Date :2018/2/12 10:04

*/

public class AuthService {

? ? /**

? ? * 獲取權限token

? ? * @return 返回示例:

? ? * {

? ? * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",

? ? * "expires_in": 2592000

? ? * }

? ? */

? ? public static String getAuth() {

? ? ? ? // 官網獲取的 API Key 更新為你注冊的

? ? ? ? String clientId = "**";

? ? ? ? // 官網獲取的 Secret Key 更新為你注冊的

? ? ? ? String clientSecret = "**";

? ? ? ? return getAuth(clientId, clientSecret);

? ? }

? ? /**

? ? * 獲取API訪問token

? ? * 該token有一定的有效期,需要自行管理,當失效時需重新獲取.

? ? * @param ak - 百度云官網獲取的 API Key

? ? * @param sk - 百度云官網獲取的 Securet Key

? ? * @return assess_token 示例:

? ? * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"

? ? */

? ? private static String getAuth(String ak, String sk) {

? ? ? ? // 獲取token地址

? ? ? ? String authHost = "https://aip.baidubce.com/oauth/2.0/token?";

? ? ? ? String getAccessTokenUrl = authHost

? ? ? ? ? ? ? ? // 1. grant_type為固定參數

? ? ? ? ? ? ? ? + "grant_type=client_credentials"

? ? ? ? ? ? ? ? // 2. 官網獲取的 API Key

? ? ? ? ? ? ? ? + "&client_id=" + ak

? ? ? ? ? ? ? ? // 3. 官網獲取的 Secret Key

? ? ? ? ? ? ? ? + "&client_secret=" + sk;

? ? ? ? try {

? ? ? ? ? ? URL realUrl = new URL(getAccessTokenUrl);

? ? ? ? ? ? // 打開和URL之間的連接

? ? ? ? ? ? HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

? ? ? ? ? ? connection.setRequestMethod("GET");

? ? ? ? ? ? connection.connect();

? ? ? ? ? ? // 獲取所有響應頭字段

? ? ? ? ? ? Map<String, List<String>> map = connection.getHeaderFields();

? ? ? ? ? ? // 遍歷所有的響應頭字段

? ? ? ? ? ? for (String key : map.keySet()) {

? ? ? ? ? ? ? ? System.err.println(key + "--->" + map.get(key));

? ? ? ? ? ? }

? ? ? ? ? ? // 定義 BufferedReader輸入流來讀取URL的響應

? ? ? ? ? ? BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

? ? ? ? ? ? StringBuilder result = new StringBuilder();

? ? ? ? ? ? String line;

? ? ? ? ? ? while ((line = in.readLine()) != null) {

? ? ? ? ? ? ? ? result.append(line);

? ? ? ? ? ? }

? ? ? ? ? ? /**

? ? ? ? ? ? * 返回結果示例

? ? ? ? ? ? */

? ? ? ? ? ? System.err.println("result:" + result);

? ? ? ? ? ? JSONObject jsonObject = new JSONObject(result.toString());

? ? ? ? ? ? return jsonObject.getString("access_token");

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? System.err.printf("獲取token失敗!");

? ? ? ? ? ? e.printStackTrace(System.err);

? ? ? ? }

? ? ? ? return null;

? ? }

? ? public static void main(String[] args) {

? ? ? ? getAuth();

? ? }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

3. 編寫將圖片轉化成base64后再轉化成urlencode的工具類

package com.wsk.netty.check;

import sun.misc.BASE64Encoder;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.URLEncoder;

/**

* 圖片轉化base64后再UrlEncode結果

* @Author : WuShukai

* @Date :2018/2/12 10:43

*/

public class BaseImg64 {

? ? /**

? ? * 將一張本地圖片轉化成Base64字符串

? ? * @param imgPath 本地圖片地址

? ? * @return 圖片轉化base64后再UrlEncode結果

? ? */

? ? public static String getImageStrFromPath(String imgPath) {

? ? ? ? InputStream in;

? ? ? ? byte[] data = null;

? ? ? ? // 讀取圖片字節數組

? ? ? ? try {

? ? ? ? ? ? in = new FileInputStream(imgPath);

? ? ? ? ? ? data = new byte[in.available()];

? ? ? ? ? ? in.read(data);

? ? ? ? ? ? in.close();

? ? ? ? } catch (IOException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? ? ? // 對字節數組Base64編碼

? ? ? ? BASE64Encoder encoder = new BASE64Encoder();

? ? ? ? // 返回Base64編碼過再URLEncode的字節數組字符串

? ? ? ? return URLEncoder.encode(encoder.encode(data));

? ? }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

.

4. 編寫調用百度API接口的方法,獲取識別結果

package com.wsk.netty.check;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import java.io.File;

import java.io.IOException;

import java.net.URI;

import java.net.URISyntaxException;

/**

* 圖像文字識別

*

* @Author : WuShukai

* @Date :2018/2/12 10:25

*/

public class Check {

? ? private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + AuthService.getAuth();

? ? /**

? ? * 識別本地圖片的文字

? ? *

? ? * @param path 本地圖片地址

? ? * @return 識別結果,為json格式

? ? * @throws URISyntaxException URI打開異常

? ? * @throws IOException? ? ? ? io流異常

? ? */

? ? public static String checkFile(String path) throws URISyntaxException, IOException {

? ? ? ? File file = new File(path);

? ? ? ? if (!file.exists()) {

? ? ? ? ? ? throw new NullPointerException("圖片不存在");

? ? ? ? }

? ? ? ? String image = BaseImg64.getImageStrFromPath(path);

? ? ? ? String param = "image=" + image;

? ? ? ? return post(param);

? ? }

? ? /**

? ? * @param url 圖片url

? ? * @return 識別結果,為json格式

? ? */

? ? public static String checkUrl(String url) throws IOException, URISyntaxException {

? ? ? ? String param = "url=" + url;

? ? ? ? return post(param);

? ? }

? ? /**

? ? * 通過傳遞參數:url和image進行文字識別

? ? *

? ? * @param param 區分是url還是image識別

? ? * @return 識別結果

? ? * @throws URISyntaxException URI打開異常

? ? * @throws IOException? ? ? ? IO流異常

? ? */

? ? private static String post(String param) throws URISyntaxException, IOException {

? ? ? ? //開始搭建post請求

? ? ? ? HttpClient httpClient = new DefaultHttpClient();

? ? ? ? HttpPost post = new HttpPost();

? ? ? ? URI url = new URI(POST_URL);

? ? ? ? post.setURI(url);

? ? ? ? //設置請求頭,請求頭必須為application/x-www-form-urlencoded,因為是傳遞一個很長的字符串,不能分段發送

? ? ? ? post.setHeader("Content-Type", "application/x-www-form-urlencoded");

? ? ? ? StringEntity entity = new StringEntity(param);

? ? ? ? post.setEntity(entity);

? ? ? ? HttpResponse response = httpClient.execute(post);

? ? ? ? System.out.println(response.toString());

? ? ? ? if (response.getStatusLine().getStatusCode() == 200) {

? ? ? ? ? ? String str;

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? /*讀取服務器返回過來的json字符串數據*/

? ? ? ? ? ? ? ? str = EntityUtils.toString(response.getEntity());

? ? ? ? ? ? ? ? System.out.println(str);

? ? ? ? ? ? ? ? return str;

? ? ? ? ? ? } catch (Exception e) {

? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? ? ? return null;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return null;

? ? }

? ? public static void main(String[] args) {

? ? ? ? String path = "E:\\find.png";

? ? ? ? try {

? ? ? ? ? ? long now = System.currentTimeMillis();

? ? ? ? ? ? checkFile(path);

? ? ? ? ? ? checkUrl("https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=08c05c0e8444ebf8797c6c6db890bc4f/fc1f4134970a304e46bfc5f7d2c8a786c9175c19.jpg");

? ? ? ? ? ? System.out.println("耗時:" + (System.currentTimeMillis() - now) / 1000 + "s");

? ? ? ? } catch (URISyntaxException | IOException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

.

5. 識別結果(僅測試本地圖片識別)

中文


結果:


結論

這里是使用了Postman進行測試的,用IDEA控制臺的話,返回的json不易讀。

從這里可以看出,耗時是1s,雖然識別率高,但是結果還是有那么的一些差距,例如識別結果的第五列,只返回了“我是遜尼”,而原圖片的很大串沒有識別出來。

英文:


結果:


結論

單識別英文的圖片,效果還是比較滿意的,耗時短,精準率高。

中英文結合:


結果:


如果你想學好JAVA這門技術,也想在IT行業拿高薪,可以參加我們的訓練營課程,選擇最適合自己的課程學習,技術大牛親授,8個月后,進入名企拿高薪。我們的課程內容有:Java工程化、高性能及分布式、高性能、深入淺出。高架構。性能調優、Spring,MyBatis,Netty源碼分析和大數據等多個知識點。如果你想拿高薪的,想學習的,想就業前景好的,想跟別人競爭能取得優勢的,想進阿里面試但擔心面試不過的,你都可以來,q群號為:180705916 進群免費領取學習資料。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,886評論 18 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,759評論 18 399
  • 如何避免失業危機?平時注意增加學歷、培養跳槽技能、開發副業 一是首先從戰略上對自己的人生要有個定位,十年后你想過一...
    思維燈泡閱讀 225評論 0 0
  • 出租車司機,是現代城市中普普通通、而又必不可少的職業。 絕大多數人都坐過出租,也許,在短暫的乘車途中,你還和他們有...
    風羽白閱讀 630評論 0 2