General OCR API 호출 가이드

페이지 이동경로

General OCR API Reference

카카오 i 클라우드의 General OCR API를 호출할 때 필요한 개발 정보는 다음과 같습니다.

API 정보

General OCR API는 다음의 형식을 따릅니다.

POST /ai/{service name}/{signature} HTTP/1.1 
Host: {host} 
x-api-key: {AI API Key}
content-type: multipart/form-data
파라미터 타입 필수여부 설명
service name String 필수 서비스(API)명 입력
- OCR로 고정
signature String 필수 API Endpoint URL의 경로(Path)
- 도메인목록 > AI API 인증정보 > API Endpoint URL에서 조회
host String 필수 API Endpoint URL의 호스트(Host)
- 도메인목록 > AI API 인증정보 > API Endpoint URL에서 조회
AI API Key String 필수 Kakao i Cloud Console에서 발급받은 AI API 키 정보로 API 호출 시 필요
- API를 호출하는 주체를 구별하기 위한 고유의 식별자로, 암호화가 되어 있음
- 도메인목록 > AI API 인증정보 > AI API Key에서 조회
content-type String 필수 다음의 방식을 지원
- multipart/form-data

API 호출 방식

General OCR API의 호출 방식은 다음과 같이 두 가지 방식을 지원합니다.

메서드 구분 설명
POST Header application/x-www-form-urlencoded
  Header application/json

General OCR API

Request

Request Syntax

코드 예제 Request Syntax

curl --location --request POST 'https://14869487-63b5-4523-be93-8959ad660b3d.api.kr-central-1.kakaoi.io/ocr/services/general-ocr/e3bd4a3e261e44fc9c2e5c30602ee29f' \
--header 'x-api-key: c7c139b64419fe589c0f1db00658e9e9' \
--header 'Content-Type: multipart/form-data' \
--form 'image=@"/Users/kakao/Projects/filepath.github.io/_posts/why-use-webflux/thread_blocking.png"'

Request Elements

파라미터 타입 필수여부 설명
image Binary 필수 이미지 파일

Response

Response Syntax

코드 예제 Response Syntax

{
    "responses": [
        {
            "page": 1,
            "results": [{
                    "box": [
                        [
                            67,
                            20
                        ],
                        [
                            308,
                            20
                        ],
                        [
                            308,
                            91
                        ],
                        [
                            67,
                            91
                        ]
                    ],
                    "recognized_word": [
                        "초미세먼지"
                    ]
                }, {
                    "box": [
                        [
                            151,
                            290
                        ],
                        [
                            227,
                            283
                        ],
                        [
                            229,
                            293
                        ],
                        [
                            152,
                            301
                        ]
                    ],
                    "recognized_word": [
                        "CarService"
                    ]
                }
            ]
        }
    ]
}

Response Elements

필드 타입 필수여부 설명 비고
responses ▼ Array 필수 각 페이지 별 OCR 인식 결과  
   pages Number 필수 인식 결과의 페이지 번호  
   results ▼ Array 필수 인식된 문자 영역 결과  
     box Array 필수 인식된 문자 영역에 대한 x와 y 좌표(원본 이미지 기준 픽셀 좌표)
- 형식: [[좌상단x, 좌상단y], [우상단x, 우상단y], [우하단x, 우하단y], [좌하단x, 좌하단y]]
   - 상단과 하단은 모니터의 위, 아래를 가르키며 x 좌표는 왼쪽에서 오른쪽으로 갈수록, y 좌표는 위에서 아래로 갈수록 증가
 
     recongnized_word Array 필수 문자 영역에 있는 이미지를 텍스트로 변환한 결과 값  

Status Code

응답 코드 응답 내용 설명
200 - API 호출 성공
400 Bad Request 요청 주소가 잘못된 경우
  INVALID_SIGNATURE 요청 Endpoint 주소의 signature가 잘못된 경우
  NO_IMAGE 이미지 데이터를 인식할 수 없음
401 Authentication failed x-api-key 헤더가 없거나 값이 잘못된 경우
404 NOT FOUND 지원하지 않는 Method로 요청을 보낸 경우
405 Method Not Allowed 지원하지 않는 Method로 요청을 보낸 경우
  TOO_MANY_BOXES 문자 영역 개수 초과
- 최대 문자 영역 개수: 100개
  UNSUPPORTED_IMAGE_FORMAT 지원하지 않는 이미지 포맷
413 Request Entity Too Large 요청의 크기가 제한보다 큰 경우
- 최대 용량 : 8MB
  EXCEED_MAX_LEN 요청 이미지 px 초과
  EXCEED_MAX_PAGES 요청 PDF 페이지 수 초과
- 최대 페이지 수 : 30장
415 Unsupported content type Content Type 헤더가 없거나 규격에 맞지 않는 경우
425 Domain not found 요청한 도메인이 삭제되어 없을 경우
  Domain not deployed 요청한 도메인이 아직 배포되지 않은 경우
429 Too many Requests 설정한 한도를 초과해서 요청한 경우
503 INTERNAL ERROR 예상하지 못한 서버 오류가 발생한 경우

안내
위에 제시된 OCR API 성능보다 더 높은 성능이 필요한 경우에는 헬프데스크 > 기술문의 또는 상담 및 도입 문의 신청으로 문의하시기 바랍니다.

부록. Python으로 General OCR API 사용하기

API 호출

requests 모듈을 활용해 General OCR API를 호출하는 코드 예제입니다.

코드 예제 API 호출 Sample Code

import requests

api_key = "OCR > 도메인 > 인증 정보의 API Key"
url = "OCR > 도메인 > 인증 정보의 API Endpoint URL"
image_path = "path/to/image"

headers = {"x-api-key": api_key}
files = {"image": open(image_path)}

response = requests.post(url=url, headers=headers, files=files)
print(response)

"""
응답 예시

{
    "responses": [
        {
            "page": 1,
            "results": [{
                    "box": [
                        [67, 20],
                        [308, 20],
                        [308, 91],
                        [67, 91]
                    ],
                    "recognized_word": [
                        "초미세먼지"
                    ]
                }, {
                    "box": [
                        [151, 290],
                        [227, 283],
                        [229, 293],
                        [152, 301]
                    ],
                    "recognized_word": [
                        "CarService"
                    ]
                }
            ]
        }
    ]
}
"""

이미지 크기 조정

최대 크기 제한에 맞춰 이미지 크기를 조정한 후 API 요청을 보내는 코드 예제입니다.

코드 예제 이미지 크기 조정 Sample Code

import cv2
import numpy as np
import requests

def load_image(image_path: str) -> np.ndarray:
    return cv2.imread(image_path)

def resize_image(image: np.ndarray, max_pixels: int = 4096) -> np.ndarray:
    height, width, _ = image.shape
    resize_ratio = 1

    if height > max_pixels or width > max_pixels:
        resize_ratio = max_pixels / max(height, width)
        image = cv2.resize(image, None, fx=resize_ratio, fy=resize_ratio)

    return image, resize_ratio

api_key = "OCR > 도메인 > 인증 정보 의 API Key"
url = "OCR > 도메인 > 인증 정보 의 API Endpoint URL"
image_path = "path/to/image"

image = load_image(image_path)
resized_image, resize_ratio = resize_image(image)
response = ocr(resized_image, url, api_key)
print(response)

문자 영역 크롭 이미지 생성

API 응답을 바탕으로 인식된 문자 영역을 원본 이미지에서 잘라내는 코드 예제입니다.

코드 예제 문자 영역 크롭 이미지 생성 Sample Code

import cv2
import numpy as np
import requests

def crop_image(
    image: np.ndarray, box: list[list], resize_ratio: float = 1.0
) -> np.ndarray:
    left_top_x = int(box[0][0] / resize_ratio)
    right_top_x = int(box[1][0] / resize_ratio)
    left_top_y = int(box[0][1] / resize_ratio)
    left_bottom_y = int(box[3][1] / resize_ratio)

    return image[left_top_y:left_bottom_y, left_top_x:right_top_x]

크롭 이미지 확인

생성된 문자 영역 이미지를 하나씩 확인하는 코드 예제입니다.

코드 예제 크롭 이미지 확인 Sample Code

api_key = "OCR > 도메인 > 인증 정보 의 API Key"
url = "OCR > 도메인 > 인증 정보 의 API Endpoint URL"
image_path = "path/to/image"

image = load_image(image_path)
resized_image, resize_ratio = resize_image(image)
response = ocr(resized_image, url, api_key)
for response in response["responses"]:
    for result in response["results"]:
        box = result["box"]
        text = "".join(result["recognized_word"])

        cropped_image = crop_image(image, box, resize_ratio)
        cv2.imshow(text, cropped_image)
        cv2.waitKey(0)
        cv2.destroyWindow(text)

Sample Code

전체 코드 예제는 다음과 같습니다.

코드 예제 General OCR API 활용 Sample Code

import cv2
import numpy as np
import requests


def load_image(image_path: str) -> np.ndarray:
    return cv2.imread(image_path)


def resize_image(image: np.ndarray, max_pixels: int = 4096) -> np.ndarray:
    height, width, _ = image.shape
    resize_ratio = 1

    if height > max_pixels or width > max_pixels:
        resize_ratio = max_pixels / max(height, width)
        image = cv2.resize(image, None, fx=resize_ratio, fy=resize_ratio)

    return image, resize_ratio


def ocr(image: np.ndarray, url: str, api_key: str) -> dict:
    image = cv2.imencode(".png", image)[1]
    image = image.tobytes()

    headers = {"x-api-key": api_key}

    files = {"image": image}

    response = requests.post(url=url, headers=headers, files=files)

    return response.json()


def crop_image(
    image: np.ndarray, box: list[list], resize_ratio: float = 1.0
) -> np.ndarray:
    left_top_x = int(box[0][0] / resize_ratio)
    right_top_x = int(box[1][0] / resize_ratio)
    left_top_y = int(box[0][1] / resize_ratio)
    left_bottom_y = int(box[3][1] / resize_ratio)

    return image[left_top_y:left_bottom_y, left_top_x:right_top_x]


if __name__ == "__main__":
    api_key = "OCR > 도메인 > 인증 정보 의 API Key"
    url = "OCR > 도메인 > 인증 정보 의 API Endpoint URL"
    image_path = "path/to/image"

    image = load_image(image_path)
    resized_image, resize_ratio = resize_image(image)
    response = ocr(resized_image, url, api_key)
    for response in response["responses"]:
        for result in response["results"]:
            box = result["box"]
            text = "".join(result["recognized_word"])

            cropped_image = crop_image(image, box, resize_ratio)
            cv2.imshow(text, cropped_image)
            cv2.waitKey(0)
            cv2.destroyWindow(text)