java多种方法实现图片OCR示例代码
时间: 2023-04-11 08:01:11 浏览: 154
以下是一个使用Java多种方法实现图片OCR的示例代码:
1. 使用Tesseract OCR库:
```
import net.sourceforge.tess4j.*;
public class ImageOCR {
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());
}
}
}
```
2. 使用Google Cloud Vision API:
```
import com.google.cloud.vision.v1.*;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ImageOCR {
public static void main(String[] args) throws IOException {
Path imagePath = Paths.get("image.png");
byte[] imageBytes = Files.readAllBytes(imagePath);
ByteString byteString = ByteString.copyFrom(imageBytes);
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
Image image = Image.newBuilder().setContent(byteString).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
.addFeatures(Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION))
.setImage(image)
.build();
BatchAnnotateImagesResponse response = client.batchAnnotateImages(ImmutableList.of(request));
TextAnnotation textAnnotation = response.getResponses(0).getFullTextAnnotation();
System.out.println(textAnnotation.getText());
}
}
}
```
3. 使用OpenCV和Tesseract OCR库:
```
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import net.sourceforge.tess4j.*;
public class ImageOCR {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat image = Imgcodecs.imread("image.png");
Mat gray = new Mat();
Imgproc.cvtColor(image, gray, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(gray, gray, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(gray);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
}
```
阅读全文