java圖像識別,英文識別 java_Java-百度API的圖片文字識別(支持英文)

 2023-11-12 阅读 21 评论 0

摘要:PS:基于Java 1.8java圖像識別、版本控制:maven使用之前需要獲取對應的項目API_KEY,SECRET_KEY,這些參數在使用API的時候必須用到,用于生成access_token。如何獲取這些參數:在百度開發者中心申請一個“通用文字識別”項目,然

PS:

基于Java 1.8

java圖像識別、版本控制:maven

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

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

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

1. 準備pom文件

com.alibaba

java中文怎么讀?fastjson

1.2.46

org.apache.httpcomponents

java常用單詞大全。httpclient

4.5.5

2. 獲取access_tokenpackage 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;/**

java英語單詞發音,* 獲取token類

*

* @Author : WuShukai

java必備英語單詞?* @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> 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();

}

}

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));

}

}

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

}

}

}

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

中文

9cff92a762e964ac38895d3d52cf2fe0.png

結果:

1d35cff4ef4d724d6b28ced2c761ecc0.png

結論

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

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

英文:

54e0eba44e330ab99133a62d8e5249fa.png

結果:

a82b68ed6ab1443e1fca2683d852a729.png

結論

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

中英文結合:

bc80b41ad24ecf31ef19344640d8f716.png

結果:

b9cf52a1af572c8974db5c27774852e7.png

結論

結果也是比較滿意的。百度的識別還是要雙擊66666.

具體文檔:http://ai.baidu.com/docs#/OCR-API/e1bd77f3

PS:

基于Java 1.8

版本控制:maven

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

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

準備條件都完成了,現在開始進行圖像識別了。test4j圖片文字識別教程:http://blog.csdn.net/wsk1103/article/details/54173282

1. 準備pom文件

com.alibaba

fastjson

1.2.46

org.apache.httpcomponents

httpclient

4.5.5

2. 獲取access_tokenpackage 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> 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();

}

}.

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));

}

}

.

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

}

}

}

.

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

中文

f6a8cc17ec9a3b827f615a479ec36301.png

結果:

a755c86d1dd09ba2fc784a842e1e138a.png

結論

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

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

英文:

46e05bcc740598e8831996994053acd8.png

結果:

3b08daccf8b6f580473790ba38161a08.png

結論

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

中英文結合:

4f2439627ad52eef4a55af7f0ab5344f.png

結果:

0fe979b77f9dfa56e7f9390fc6ddb26f.png

結論

結果也是比較滿意的。

相關推薦:

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/172281.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息