본문 바로가기
개발/Java

[JAVA] OCR - Google Vision

by 바이너리10 2021. 6. 28.
반응형

구글 비전의 목적

  • 광학 문자 인식 OCR(Optical character recognition)
  • 임의의 이미지에서 텍스트를 감지하고 추출합니다. 간판이나 표지판이 찍힌 사진을 예시로 들 수 있습니다. 

구글 비전의 장점

  • 한글 인식률이 생각보다 높다

 

구글 비전의 단점

  • 비용 발생
  • 수량 처음 1,000개 단위 월단위 1,001 ~ 5,000,000개 월단위 5,000,001개 이상/월
    가격 무료 $1.50 $0.60

구현

<!-- https://mvnrepository.com/artifact/com.google.cloud/google-cloud-vision -->
<dependency>
	<groupId>com.google.cloud</groupId>
	<artifactId>google-cloud-vision</artifactId>
	<version>1.75.0</version>
</dependency>
package spider.binaries.app.util;


import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.protobuf.ByteString;

public class GoogleVisionTest {

	public static void main(String[] args) {
		    File credentialsPath = new File("Path/fileName.json");
			// Load credentials from JSON key file. If you can't set the GOOGLE_APPLICATION_CREDENTIALS
			// environment variable, you can explicitly load the credentials file to construct the
			// credentials.
			GoogleCredentials credentials;
			try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
			   credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
			}

			
			String imageFilePath = newFileName; //여기에는 자신의 로컬 경로 파일명
			List<AnnotateImageRequest> requests = new ArrayList<>();
			ByteString imgBytes = ByteString.readFrom(new FileInputStream(imageFilePath));
			Image img = Image.newBuilder().setContent(imgBytes).build();
			Feature feat = Feature.newBuilder().setType(Type.TEXT_DETECTION).build();
			AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
			requests.add(request);
			//Setting the credentials:
			  ImageAnnotatorSettings imageAnnotatorSettings = ImageAnnotatorSettings.newBuilder()
			   .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
			   .build();
			  
			
			try (ImageAnnotatorClient client = ImageAnnotatorClient.create(imageAnnotatorSettings)) {
					BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
					List<AnnotateImageResponse> responses = response.getResponsesList();
					for (AnnotateImageResponse res : responses) {
						if (res.hasError()) {
							System.out.printf("Error: %s\n", res.getError().getMessage());
							return res.getError().getMessage();
						}
						// // For full list of available annotations, see http://g.co/cloud/vision/docs
						// TextAnnotation annotation = res.getFullTextAnnotation();
						// for (Page page: annotation.getPagesList()) {
						// String pageText = "";
						// for (Block block : page.getBlocksList()) {
						// String blockText = "";
						// for (Paragraph para : block.getParagraphsList()) {
						// String paraText = "";
						// for (Word word: para.getWordsList()) {
						// String wordText = "";
						// for (Symbol symbol: word.getSymbolsList()) {
						// wordText = wordText + symbol.getText();
						// System.out.format("Symbol text: %s (confidence: %f)\n", symbol.getText(),
						// symbol.getConfidence());
						// }
						// System.out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence());
						// paraText = String.format("%s %s", paraText, wordText);
						// }
						// // Output Example using Paragraph:
						// System.out.println("\nParagraph: \n" + paraText);
						// System.out.format("Paragraph Confidence: %f\n", para.getConfidence());
						// blockText = blockText + paraText;
						// }
						// pageText = pageText + blockText;
						// }
						// }
						// System.out.println("\nComplete annotation:");
						// System.out.println(annotation.getText());
						// }
						System.out.println("Text : ");
						System.out.println(res.getTextAnnotationsList().get(0).getDescription());
						
						// For full list of available annotations, see http://g.co/cloud/vision/docs
//						for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
//							System.out.printf("Text: %s\n", annotation.getDescription());
////							System.out.printf("Position : %s\n", annotation.getBoundingPoly()); 
//						}
						
					}
			
					
			}
	}
	
	
}

 

설치시 주의 사항

 

 

출처 : https://cloud.google.com/vision/docs/ocr?hl=ko 

          https://cloud.google.com/vision/pricing?hl=ko

 

 

이미지의 텍스트 감지  |  Cloud Vision API  |  Google Cloud

이 API를 모바일 앱에서 사용하는 경우 Firebase 머신러닝 및 ML Kit를 사용해 보세요. 이 키트는 Cloud Vision 서비스를 사용하기 위한 네이티브 Android 및 iOS SDK와 함께 커스텀 ML 모델을 사용하는 기기별

cloud.google.com

 

가격 책정  |  Cloud Vision API  |  Google Cloud

Cloud Vision API는 이미지를 분석하기 위한 여러 기능을 제공합니다. 아래 시나리오에서는 선불 약정 없이 사용한 만큼만 지불하면 됩니다. 이 API에서 지원하는 기능은 다음과 같습니다. 기능 유형

cloud.google.com

 

 

 

 

반응형

'개발 > Java' 카테고리의 다른 글

[Java] PDF - iText  (0) 2021.07.12
[Java] PDF - pdfbox  (0) 2021.07.08
[Java ] OCR - 결과 비교 Tesseract, Google Vision  (2) 2021.07.02
[JAVA] OCR - tesseract  (0) 2021.06.26