광학 문자 인식(OCR)으로 필기 입력 감지
Vision API는 이미지에서 텍스트를 감지하고 추출할 수 있습니다.
DOCUMENT_TEXT_DETECTION은 이미지(또는 파일)에서 텍스트를 추출하지만, 응답이 밀집 텍스트와 문서에 맞게 최적화됩니다. JSON은 페이지, 블록, 단락, 단어, 줄바꿈 정보를 포함합니다.
DOCUMENT_TEXT_DETECTION의 한 가지 구체적인 용도는 이미지에서 필기 입력을 감지하는 것입니다.

직접 사용해 보기
Google Cloud를 처음 사용하는 경우 계정을 만들어 실제 시나리오에서 Cloud Vision API의 성능을 평가할 수 있습니다. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
Cloud Vision API 무료로 사용해 보기문서 텍스트 감지 요청
Google Cloud 프로젝트 및 인증 설정
아직 Google Cloud 프로젝트를 만들지 않았다면 지금 만드세요. 이 섹션을 펼쳐서 안내를 참조하세요.
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vision API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. -
Install the Google Cloud CLI.
-
외부 ID 프로바이더(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.
-
gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.
gcloud init -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vision API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. -
Install the Google Cloud CLI.
-
외부 ID 프로바이더(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.
-
gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.
gcloud init - BASE64_ENCODED_IMAGE: 바이너리 이미지 데이터의 base64 표현(ASCII 문자열)입니다. 이 문자열은 다음 문자열과 비슷해야 합니다.
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
- PROJECT_ID: Google Cloud 프로젝트 ID입니다.
로컬 이미지의 문서 텍스트 인식
Vision API를 사용하여 로컬 이미지 파일에서 기능 감지를 수행할 수 있습니다.
REST 요청의 경우 이미지 파일의 콘텐츠를 요청 본문에 base64로 인코딩된 문자열로 보냅니다.
gcloud 및 클라이언트 라이브러리 요청의 경우 요청에 로컬 이미지 경로를 지정합니다.
REST
요청 데이터를 사용하기 전에 다음을 바꿉니다.
HTTP 메서드 및 URL:
POST https://vision.googleapis.com/v1/images:annotate
JSON 요청 본문:
{
"requests": [
{
"image": {
"content": "BASE64_ENCODED_IMAGE"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
요청을 보내려면 다음 옵션 중 하나를 선택합니다.
curl
요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/images:annotate"
PowerShell
요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.
대응
{
"responses": [
{
"textAnnotations": [
{
"locale": "en",
"description": "O Google Cloud Platform\n",
"boundingPoly": {
"vertices": [
{
"x": 14,
"y": 11
},
{
"x": 279,
"y": 11
},
{
"x": 279,
"y": 37
},
{
"x": 14,
"y": 37
}
]
}
},
],
"fullTextAnnotation": {
"pages": [
{
"property": {
"detectedLanguages": [
{
"languageCode": "en"
}
]
},
"width": 281,
"height": 44,
"blocks": [
{
"property": {
"detectedLanguages": [
{
"languageCode": "en"
}
]
},
"boundingBox": {
"vertices": [
{
"x": 14, "y": 11
},
{
"x": 279, "y": 11
},
{
"x": 279, "y": 37
},
{
"x": 14, "y": 37
}
]
},
"paragraphs": [
{
"property": {
"detectedLanguages": [
{
"languageCode": "en"
}
]
},
"boundingBox": {
"vertices": [
{
"x": 14, "y": 11
},
{
"x": 279, "y": 11
},
{
"x": 279, "y": 37
},
{
"x": 14, "y": 37
}
]
},
"words": [
{
"property": {
"detectedLanguages": [
{
"languageCode": "en"
}
]
},
"boundingBox": {
"vertices": [
{
"x": 14, "y": 11
},
{
"x": 23, "y": 11
},
{
"x": 23, "y": 37
},
{
"x": 14, "y": 37
}
]
},
"symbols": [
{
"property": {
"detectedLanguages": [
{
"languageCode": "en"
}
],
"detectedBreak": {
"type": "SPACE"
}
},
"boundingBox": {
"vertices": [
{
"x": 14, "y": 11
},
{
"x": 23, "y": 11
},
{
"x": 23, "y": 37
},
{
"x": 14, "y": 37
}
]
},
"text": "O"
}
]
},
]
}
],
"blockType": "TEXT"
}
]
}
],
"text": "Google Cloud Platform\n"
}
}
]
}
Go
이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 Vision Go API 참고 문서를 확인하세요.
Vision에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
// detectDocumentText gets the full document text from the Vision API for an image at the given file path.
func detectDocumentText(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
image, err := vision.NewImageFromReader(f)
if err != nil {
return err
}
annotation, err := client.DetectDocumentText(ctx, image, nil)
if err != nil {
return err
}
if annotation == nil {
fmt.Fprintln(w, "No text found.")
} else {
fmt.Fprintln(w, "Document Text:")
fmt.Fprintf(w, "%q\n", annotation.Text)
fmt.Fprintln(w, "Pages:")
for _, page := range annotation.Pages {
fmt.Fprintf(w, "\tConfidence: %f, Width: %d, Height: %d\n", page.Confidence, page.Width, page.Height)
fmt.Fprintln(w, "\tBlocks:")
for _, block := range page.Blocks {
fmt.Fprintf(w, "\t\tConfidence: %f, Block type: %v\n", block.Confidence, block.BlockType)
fmt.Fprintln(w, "\t\tParagraphs:")
for _, paragraph := range block.Paragraphs {
fmt.Fprintf(w, "\t\t\tConfidence: %f", paragraph.Confidence)
fmt.Fprintln(w, "\t\t\tWords:")
for _, word := range paragraph.Words {
symbols := make([]string, len(word.Symbols))
for i, s := range word.Symbols {
symbols[i] = s.Text
}
wordText := strings.Join(symbols, "")
fmt.Fprintf(w, "\t\t\t\tConfidence: %f, Symbols: %s\n", word.Confidence, wordText)
}
}
}
}
}
return nil
}
Java
이 샘플을 시도하기 전에 Vision API 빠른 시작: 클라이언트 라이브러리 사용의 Java 설정 안내를 따르세요. 자세한 내용은 Vision API Java 참고 문서를 확인하세요.
public static void detectDocumentText(String filePath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response