ocr java 代码
时间: 2023-07-09 21:49:30 浏览: 159
以下是一个使用Java进行OCR(光学字符识别)的示例代码:
```
import net.sourceforge.tess4j.*;
import java.io.File;
public class OCRDemo {
public static void main(String[] args) {
File imageFile = new File("image.png");
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
}
```
该代码使用了Tess4J库,首先需要将其添加到项目中。示例代码中的“image.png”是输入的图像文件名,可替换为自己的文件名。`doOCR()`方法将返回识别的字符串结果。
相关问题
用java实现OCR示例代码
我可以回答这个问题。以下是一个使用Java实现OCR的示例代码:
import java.io.File;
import net.sourceforge.tess4j.*;
public class OCRExample {
public static void main(String[] args) {
File imageFile = new File("image.png");
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
}
这个示例使用了Tesseract OCR引擎,可以识别图片中的文本并输出到控制台。
java代码 ocr文字识别
以下是Java实现OCR文字识别的代码示例:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class OCRDemo {
public static void main(String[] args) {
try {
URL url = new URL("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
String param = "image=" + URLEncoder.encode(getImageStr("test.png"), "UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(param.getBytes());
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
System.out.println(stringBuilder.toString());
bufferedReader.close();
inputStream.close();
connection.disconnect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String getImageStr(String imagePath) {
String imageStr = "";
try {
File file = new File(imagePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
imageStr = Base64.getEncoder().encodeToString(bytes);
fileInputStream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return imageStr;
}
}
```
这段代码使用了百度云OCR API进行文字识别,需要先在百度云平台上注册并创建应用,获取API Key和Secret Key。代码中的`test.png`为需要识别的图片文件名,可以根据实际情况进行修改。
阅读全文