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

使用之前需要獲取對(duì)應(yīng)的項(xiàng)目API_KEY,SECRET_KEY,這些參數(shù)在使用API的時(shí)候必須用到,用于生成access_token。

如何獲取這些參數(shù):在百度開發(fā)者中心申請(qǐng)一個(gè)“通用文字識(shí)別”項(xiàng)目,然后就可以獲取到這些參數(shù)。

準(zhǔn)備條件都完成了,現(xiàn)在開始進(jìn)行圖像識(shí)別了。

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

1. 準(zhǔn)備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 {

? ? /**

? ? * 獲取權(quán)限token

? ? * @return 返回示例:

? ? * {

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

? ? * "expires_in": 2592000

? ? * }

? ? */

? ? public static String getAuth() {

? ? ? ? // 官網(wǎng)獲取的 API Key 更新為你注冊(cè)的

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

? ? ? ? // 官網(wǎng)獲取的 Secret Key 更新為你注冊(cè)的

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

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

? ? }

? ? /**

? ? * 獲取API訪問token

? ? * 該token有一定的有效期,需要自行管理,當(dāng)失效時(shí)需重新獲取.

? ? * @param ak - 百度云官網(wǎng)獲取的 API Key

? ? * @param sk - 百度云官網(wǎng)獲取的 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為固定參數(shù)

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

? ? ? ? ? ? ? ? // 2. 官網(wǎng)獲取的 API Key

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

? ? ? ? ? ? ? ? // 3. 官網(wǎng)獲取的 Secret Key

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

? ? ? ? try {

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

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

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

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

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

? ? ? ? ? ? // 獲取所有響應(yīng)頭字段

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

? ? ? ? ? ? // 遍歷所有的響應(yīng)頭字段

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

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

? ? ? ? ? ? }

? ? ? ? ? ? // 定義 BufferedReader輸入流來讀取URL的響應(yīng)

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

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

? ? ? ? ? ? String line;

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

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

? ? ? ? ? ? }

? ? ? ? ? ? /**

? ? ? ? ? ? * 返回結(jié)果示例

? ? ? ? ? ? */

? ? ? ? ? ? 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. 編寫將圖片轉(zhuǎn)化成base64后再轉(zhuǎn)化成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;

/**

* 圖片轉(zhuǎn)化base64后再UrlEncode結(jié)果

* @Author : WuShukai

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

*/

public class BaseImg64 {

? ? /**

? ? * 將一張本地圖片轉(zhuǎn)化成Base64字符串

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

? ? * @return 圖片轉(zhuǎn)化base64后再UrlEncode結(jié)果

? ? */

? ? public static String getImageStrFromPath(String imgPath) {

? ? ? ? InputStream in;

? ? ? ? byte[] data = null;

? ? ? ? // 讀取圖片字節(jié)數(shù)組

? ? ? ? try {

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

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

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

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

? ? ? ? } catch (IOException e) {

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

? ? ? ? }

? ? ? ? // 對(duì)字節(jié)數(shù)組Base64編碼

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

? ? ? ? // 返回Base64編碼過再URLEncode的字節(jié)數(shù)組字符串

? ? ? ? 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. 編寫調(diào)用百度API接口的方法,獲取識(shí)別結(jié)果

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;

/**

* 圖像文字識(shí)別

*

* @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();

? ? /**

? ? * 識(shí)別本地圖片的文字

? ? *

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

? ? * @return 識(shí)別結(jié)果,為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 識(shí)別結(jié)果,為json格式

? ? */

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

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

? ? ? ? return post(param);

? ? }

? ? /**

? ? * 通過傳遞參數(shù):url和image進(jìn)行文字識(shí)別

? ? *

? ? * @param param 區(qū)分是url還是image識(shí)別

? ? * @return 識(shí)別結(jié)果

? ? * @throws URISyntaxException URI打開異常

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

? ? */

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

? ? ? ? //開始搭建post請(qǐng)求

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

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

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

? ? ? ? post.setURI(url);

? ? ? ? //設(shè)置請(qǐng)求頭,請(qǐng)求頭必須為application/x-www-form-urlencoded,因?yàn)槭莻鬟f一個(gè)很長的字符串,不能分段發(fā)送

? ? ? ? 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 {

? ? ? ? ? ? ? ? /*讀取服務(wù)器返回過來的json字符串?dāng)?shù)據(jù)*/

? ? ? ? ? ? ? ? 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("耗時(shí):" + (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. 識(shí)別結(jié)果(僅測(cè)試本地圖片識(shí)別)

中文


結(jié)果:


結(jié)論

這里是使用了Postman進(jìn)行測(cè)試的,用IDEA控制臺(tái)的話,返回的json不易讀。

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

英文:


結(jié)果:


結(jié)論

單識(shí)別英文的圖片,效果還是比較滿意的,耗時(shí)短,精準(zhǔn)率高。

中英文結(jié)合:


結(jié)果:


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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,728評(píng)論 18 399
  • 出租車司機(jī),是現(xiàn)代城市中普普通通、而又必不可少的職業(yè)。 絕大多數(shù)人都坐過出租,也許,在短暫的乘車途中,你還和他們有...
    風(fēng)羽白閱讀 701評(píng)論 0 2

友情鏈接更多精彩內(nèi)容