Skip to content

vision2

ocr.DetRecInferencer

학습한 모델을 사용하여 검사를 하기 위한 DetRecInferencer class 입니다.

Usage
# 인퍼런스 모듈 빌드
inferene_build_config = {
    "checkpoint_path": CHECKPOINT_PATH,
    "password": PASSWORD,
    "device": DEVICE,
}
error, inferencer = DetRecInferencer.build(inferene_build_config)
assert error >= 0

# 모듈 정보 확인
error, metadata = read_metadata(CHECKPOINT_PATH)
assert error >= 0
print("Inference metadata:", metadata)

# 인퍼런스 옵션 초기값 확인
inference_options = {
    "outputs.time": False,
    "detection.polygon_score_threshold": 0.9,
    "detection.text_size_range": [0, 512],
    "recognition.text_formatting": None,
    "recognition.text_score_threshold": 0.5,
    "params.batch_size": 2,
    "params.max_num_of_text_objects": 4,
    "params.inspection_size_wh": [512, 512],
    "params.oversized_image_handling": "resize_to_fit",
}
print("Default inference options:")
for key in inference_options:
    error, value = inferencer.get_default_inference_option(key)
    assert error >= 0
    print(f"  {key}: {value}")

# 디벨로퍼: 인퍼런스 옵션 변경
for key, value in inference_options.items():
    error, _ = inferencer.set_inference_option(key, value)
    assert error >= 0

# 디벨로퍼: metadata에 inference_option 저장 (예시)
metadata["inference_options"] = inference_options
error, _ = write_metadata(CHECKPOINT_PATH, metadata)
assert error >= 0

# 인퍼런스 옵션이 잘 변경되었는지 확인
print("Inference options:")
for key in inference_options:
    error, value = inferencer.get_inference_option(key)
    assert error >= 0
    print(f"  {key}: {value}")

# 디벨로퍼: Analyze 수행
for image_id, image_info in DATA["validation_images"].items():
    images = {image_id: image_info}

    error, results = inferencer.analyze(images=images, labeled=True)
    assert error >= 0

# 디벨로퍼: Summary
error, results = inferencer.summarize_analysis(images=images, labeled=True)
assert error >= 0
print("Analysis summary:", results)

# 런타임: 핸들러 빌드
error, metadata = read_metadata(CHECKPOINT_PATH)
assert error >= 0
inferene_build_config["inference_options"] = metadata["inference_options"]
error, inferencer = Inferencer.build(inferene_build_config)
assert error >= 0

# 런타임 검사: 후처리까지 한번에 최적화된 연산으로 수행
image_path = DATA["validation_images"][image_id]["path"]
error, output = inferencer.infer_and_postprocess(images=[image_path])
assert error >= 0
print("Runtime (infer_and_postprocess):", output)

build(config) classmethod

Inferencer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

Inferencer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "checkpoint_path": str,     # 체크포인트 경로
    "password": Optional[str],  # 체크포인트 패스워드 (default None)
    "inference_options": Optional[Dict], # 인퍼런스 옵션 config (default None). 구조는 `get_default_inference_option`의 Keys 참고.
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecInferencer class의 instance를 반환합니다.

build_from_checkpoint(config) classmethod

Inferencer class의 instance를 생성합니다. 개별 모듈을 조합해가며 테스트하기 위한 용도의 api method 입니다.

Parameters:

Name Type Description Default
config Dict

Inferencer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "checkpoint_config": {
        "checkpoint_path_det": str,     # SceneTextDetection 체크포인트 경로
        "password_det": Optional[str],  # SceneTextDetection 체크포인트 패스워드 (default None)
        "checkpoint_path_rec": str,     # SceneTextRecognition 체크포인트 경로
        "password_rec": Optional[str],  # SceneTextRecognition 체크포인트 패스워드 (default None)
    },
    "inference_options": Optional[Dict], # 인퍼런스 옵션 config (default None). 구조는 `get_default_inference_option`의 Keys 참고.
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecInferencer class의 instance를 반환합니다.

build_built_in(config) classmethod

Inferencer class의 instance를 생성합니다. Pretrained init_weight를 auto-label에 사용하기 위한 용도의 api method 입니다.

Parameters:

Name Type Description Default
config Dict

Inferencer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "network_type": str,  # build-in model 에 사용할 detection network type. ["v2_industry", "v2_general"] 중 하나를 지정합니다.
    "inference_options": Optional[Dict],  # 인퍼런스 옵션 config (default None). 구조는 `get_default_inference_option`의 Keys 참고.
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 ocr.DetRecInferencer class의 instance를 반환합니다.

get_default_inference_option(key)

Inference & postprocess 옵션의 기본 설정 값을 반환합니다.

Parameters:

Name Type Description Default
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

사용 가능한 key와 value 목록:

{
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
    "detection.polygon_score_threshold": float,  # (default 0.9, 박스 detection confidence. 높을수록 확실한 detection 결과임을 의미.)
    "detection.text_size_range": List[int],  # (default [0, max(width, height)], 텍스트 크기 유효 범위. detection 결과 텍스트의 유효 사이즈 범위를 지정하기 위해 사용.)
    "recognition.text_formatting": Optional[Union[List[str], List[List[str]]]]  # (default None)
        - Regex Type String: "eng_lower", "eng_upper", "digits", "symbol", "kor", and user custom string.
        - None  경우엔 모델이 출력할  있는 모든 문자를 사용합니다.
        - List[str]  경우, List 내부에 포함되어 있는 모든 문자열을 합하여 문자셋을 구축합니다. 글자수에는 영향을 주지 않습니다.
        - List[List[str]]  경우, 문자 길이  위의 List[str]   위치에 지정하는 기능을 합니다.
            - 예를 들어,  문자가 영소문자 혹은 대문자 ABC  하나이고, 두번째 문자가 무조건 숫자인 경우는 아래와 같이 정의될  있습니다.
            - [["eng_lower", "ABC"], ["digit"]] -> {길이 2, 영문-숫자 순으로 출력} -> recognition 결과 예시: "A0", "b1", "a8", "C0", ...
    "recognition.text_score_threshold": float,  # (default 0.5, 텍스트 인식 Score(Confidence), 인식된 텍스트에서 각 글자에 대한 확률을 평균낸 점수.)
    "params.batch_size": int,  # recognition에 한 번에 입력되는 이미지 개수 입니다.
                               # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
                               # (default 2)
    "params.max_num_of_text_objects": int,  # `infer_and_postprocess`에 한 번에 출력할 수 있는 최대 검출 개수 입니다.
                                             # <= 0 일 경우 최대 검출 수에 제한 없이 모든 텍스트를 검출합니다.
                                             # > 0 인 값을 지정하는 경우 해당 값 이하의 텍스트 수가 검출됩니다.
                                             # 이 때 detection 검출 후 detection confidence score 로 정렬하여, confidence score 가 높은 텍스트만을 검출합니다.
                                             # (default 0)
    "params.inspection_size_wh": Optional[List[int]],  # inference를 할 때, 내부 연산이 진행되는 image size 입니다.
                                                       # input image가 inspection_size_wh 넘는 경우 aspect ratio를 유지하며 resize 됩니다.
                                                       # input image가 inspection_size_wh 보다 작은 경우 부족한 부분을 zero padding으로 채웁니다.
                                                       # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
                                                       # (default None)
    "params.oversized_image_handling": str,  # inference시 inspection_size_wh 보다 큰 이미지에 대한 핸들링 옵션 입니다.
                                             # 아래 옵션들 중 한 가지를 선택할 수 있습니다.
                                             # "do_not_inspect" - 큰 이미지가 들어오면 에러 레이즈
                                             # "resize_to_fit" - 큰 이미지가 들어오면 inspection_size_wh 로 리사이즈해서 검사
                                             # (default "do_not_inspect")
}

사용 예시:

inferencer.get_default_inference_option(key="recognition.text_formatting")
inferencer.set_inference_option(key="recognition.text_formatting", value=["ABCDEF"])

get_inference_option(key)

현재 설정된 inference & postprocess 옵션 값을 읽습니다.

Parameters:

Name Type Description Default
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

get_default_inference_option과 동일합니다.

set_inference_option(key, value)

Inference & postprocess 옵션을 설정합니다.

Parameters:

Name Type Description Default
key str

설정하고자 하는 옵션 key 입니다.

required
value Any

설정하고자 하는 옵션 value 입니다.

required

Returns:

Name Type Description
None None

None

Keys

get_default_inference_option에서 warmup이 필요한 옵션을 제외하면 동일합니다.

[
    "params.batch_size",
    "params.inspection_size_wh",
]

infer_and_postprocess(input)

image의 List를 입력으로 받아 모델 인퍼런스와 후처리를 수행합니다. (for Runtime) 실시간 검사를 위해 연산 과정이 최적화되어 있으며, 중간 결과를 제거하고 postprocess 최종 결과만을 반환합니다.

Parameters:

Name Type Description Default
input Union[List[np.ndarray], List[str]]
- List[np.ndarray]: numpy image가 들어있는 List 입니다. 각 image는 다음 제약 조건을 갖습니다.
                    data type: uint8, uint16
                    channel: H x W / H x W x 1 - Gray
                             H x W x 3 - RGB
                             H x W x 4 - RGBA
- List[str]: image 경로가 들어있는 List 입니다.
required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict]: image의 postprocess 결과들이 들어있는 List 입니다.

[
    {
        "objects": [  # OCR 결과 object들의 리스트. (List[Dict])
            {  # ocr object 구조
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
            },
            ...,  # times number of objects
        ],
        "is_oversized": bool,  # 입력한 이미지가 oversized인지 여부 (True면 oversized)
        "time": {  # inference_options에 설정된 경우에만 출력.
            "imread_time": float,
            "inference_time": float,
            "detection_inference_time": float,
            "recognition_inference_time": float,
            "detection_post_processing_time": float,
            "recognition_post_processing_time": float,
        }
    },
    ...,  # times number of images
]

analyze(images, labeled)

images들에 대한 모델 인퍼런스 후, analysis 결과 계산

Parameters:

Name Type Description Default
images Dict[str, Dict]

analysis에 사용할 데이터 리스트. Trainer 빌드에 사용하는 이미지 리스트와 동일한 구조.

{
    "{image_id}": {
        "path": str,  # 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [  # (labeled = False)인 경우 필요하지 않습니다.
            {
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
            },
            ...,  # times number of labels in the image
        ],
        "save_dir": str,  # 해당 이미지의 analysis 결과 저장 directory
    },
    ...,  # times number of images
}

required
labeled bool

label 존재 여부. label 존재 여부에 따라 analysis 결과 Dict 구성 요소가 달라집니다.

required

Returns:

Name Type Description
Dict Dict

images들에 대한 analysis 결과

{
    "{image_id}": {
        "labels": [  # "labels" 결과는 labeled=True인 경우에만 존재
            {
                "correct": bool,  # 라벨의 모든 텍스트가 검출되었는지 판별. True면 TP, False면 FN
                "correct_text": str,  # recall - 라벨 텍스트 중 맞은 텍스트
            },
            ... # 입력으로 넣어준 labels와 동일한 개수
        ],
        "predictions": {
            "objects": [
                {
                    "polygon_score": float,  # polygon confidence score
                    "text_size": float,  # text size
                    "text_score": float,  # text confidence score
                    "is_vertical": bool,  # True면 세로 텍스트, False면 가로 텍스트
                    "polygon": [
                        [float, float],
                        ..., # times number of points
                    ],
                    "text": str,
                    # 아래 항목들은 labeled=True인 경우에만 존재
                    "correct": bool,  # 모든 검출된 텍스트가 실제 라벨 중 하나에 포함되는지 판별. True면 TP, False면 FP
                    "correct_text": str,  # precision - 검출된 텍스트 중 맞은 텍스트
                },
                ..., # NOTE: 이미지 내의 검출된 텍스트 뭉치 수만큼 반복
            ],
            "is_oversized": bool,  # 입력한 이미지가 oversized인지 여부 (True면 oversized)
            "time": {  # inference_options에 설정된 경우에만 출력.
                "imread_time": float,
                "inference_time": float,  # time for `detection` + `recognition` + `intermediate steps`
                "detection_inference_time": float,
                "recognition_inference_time": float,
                "detection_post_processing_time": float,
                "recognition_post_processing_time": float,
            }
            # NOTE: 아래 항목들은 labeled=True인 경우에만 존재
            "object/underkill": int,  # 이미지 내에서 라벨 object 중 검출하지 못한 라벨의 개수 (미검)
            "object/overkill": int,  # 이미지 내에서 예측 object 중 틀린 예측의 개수 (과검)
        },
    },
    ..., # 입력으로 넣어준 이미지 개수만큼 반복
}

Note1

모델 빌드 및 인퍼런스 없이 저장되어있는 network output을 활용하여 analyze하고 싶은 경우에는 Analyzer.analyze를 호출해야 합니다.

summarize_analysis(images, labeled)

images들에 대한 analysis summary 계산

Parameters:

Name Type Description Default
images Dict[str, Dict]

analysis에 사용할 데이터 리스트. Trainer 빌드에 사용하는 이미지 리스트와 동일한 구조.

required
labeled bool

label 존재 여부. label 존재 여부에 따라 analysis 결과 Dict 구성 요소가 달라집니다.

required

Returns:

Name Type Description
Dict Dict

images들에 대한 analysis summary

# Case1: **(labeled=True)인 경우**
{
    "object/f1": float,  # object 단위 전체 검사 결과의 F1 스코어
    "text/recall": float,  # recall - 전체 라벨 텍스트 중 맞은 문자의 비율
}

# Case2: **(labeled=False)인 경우**
{} # 빈 Dict

warmup()

현재 설정된 inference 옵션을 바탕으로 warmup을 수행합니다.

change_resize_scale(images, target_text_size=32)

images로 입력된 이미지의 라벨 정보 및 target_text_size(Optional)를 이용해 resize scale을 변경합니다.

Parameters:

Name Type Description Default
images Dict[str, Dict]

analysis에 사용할 데이터 리스트. Trainer 빌드에 사용하는 이미지 리스트와 동일한 구조.

{
    "{image_id}": {
        "path": str,  # 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [  # (labeled = False)인 경우 필요하지 않습니다.
            {
                "polygon": [
                    [float, float],
                    ..., # times number of points
                ],
                "text": str,
                "class_index": int,
            },
            ...,  # times number of labels in the image
        ],
        "save_dir": str,  # 해당 이미지의 analysis 결과 저장 directory
    },
    ...,  # times number of images
}

required
target_text_size int

images의 라벨들이 변경되어야 하는 target text_size. (default 32)

32

Returns:

Name Type Description
None None

None

ocr.DetRecAnalyzer

딥러닝 모델 빌드 없이, 저장된 모델 인퍼런스 결과를 이용해서 analysis를 수행하는 클래스입니다.

Usage
# DetRecAnalyzer 빌드
error, analyzer = DetRecAnalyzer.build()
assert error >= 0

# 모듈 정보 확인
error, metadata = read_metadata(CHECKPOINT_PATH)
assert error >= 0
print("Inference metadata:", metadata)

# 인퍼런스 옵션 초기값 확인
inference_options = {
    "outputs.time": False,
    "detection.polygon_score_threshold": 0.9,
    "detection.text_size_range": [0, 512],
    "recognition.text_formatting": None,
    "recognition.text_score_threshold": 0.5,
    "params.batch_size": 2,
    "params.max_num_of_text_objects": 4,
    "params.inspection_size_wh": [512, 512],
    "params.oversized_image_handling": "resize_to_fit",
}
print("Default inference options:")
for key in list(inference_options):
    error, value = analyzer.get_default_inference_option(key)
    assert error >= 0
    print(f"  {key}: {value}")

# 디벨로퍼: Analyze 수행
for image_id, image_info in DATA["validation_images"].items():
    image_info["save_dir"] = os.path.join("./demo/inference_results", str(image_id))
    image = {image_id: image_info}

    error, results = analyzer.analyze(images=image, labeled=True)
    assert error >= 0

error, results = analyzer.summarize_analysis(images=DATA["validation_images"], labeled=True)
assert error >= 0
print("Analysis summary:", results)

# 디벨로퍼: 인퍼런스 옵션 변경
for key, value in inference_options.items():
    error, _ = analyzer.set_inference_option(key, value)
    assert error >= 0

# 디벨로퍼: metadata에 inference_option 저장 (예시)
metadata["inference_options"] = inference_options
error, _ = write_metadata(CHECKPOINT_PATH, metadata)
assert error >= 0

# 인퍼런스 옵션이 잘 변경되었는지 확인
print("Inference options:")
for key in inference_options:
    error, value = analyzer.get_inference_option(key)
    assert error >= 0
    print(f"  {key}: {value}")

# 디벨로퍼: 새로운 세팅으로 Analyze 재수행
for image_id, image_info in DATA["validation_images"].items():
    image = {image_id: image_info}

    error, results = analyzer.analyze(images=image, labeled=True)
    assert error >= 0

error, results = analyzer.summarize_analysis(images=DATA["validation_images"], labeled=True)
assert error >= 0
print("Analysis summary:", results)

build(config=None) classmethod

DetRecAnalyzer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

DetRecAnalyzer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "encoder_config": Optional[Dict[str, Any]],  # encoder 생성 config (NOTE: 현재 encoder 생성 config 가 고정되어있으므로, 넣어주지 않아도 무방)
    "inference_options": Optional[Dict], # 인퍼런스 옵션 config (default None). 구조는 `get_default_inference_option`의 Keys 참고.
}

None

Returns:

Name Type Description
DetRecAnalyzer Analyzer

build가 완료된 ocr.DetRecAnalyzer class의 instance를 반환합니다.

get_default_inference_option(key)

Postprocess 옵션의 기본 설정 값을 반환합니다.

Parameters:

Name Type Description Default
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

사용 가능한 key와 value 목록:

{
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
    "detection.polygon_score_threshold": float,  # (default 0.9, 박스 detection confidence. 높을수록 확실한 detection 결과임을 의미.)
    "detection.text_size_range": List[int],  # (default [0, max(width, height)], 텍스트 크기 유효 범위. detection 결과 텍스트의 유효 사이즈 범위를 지정하기 위해 사용.)
    "recognition.text_formatting": Optional[Union[List[str], List[List[str]]]]  # (default None)
        - Regex Type String: "eng_lower", "eng_upper", "digits", "symbol", "kor", and user custom string.
        - None  경우엔 모델이 출력할  있는 모든 문자를 사용합니다.
        - List[str]  경우, List 내부에 포함되어 있는 모든 문자열을 합하여 문자셋을 구축합니다. 글자수에는 영향을 주지 않습니다.
        - List[List[str]]  경우, 문자 길이  위의 List[str]   위치에 지정하는 기능을 합니다.
            - 예를 들어,  문자가 무조건 대문자 ABC  하나이고, 두번째 문자가 무조건 숫자인 경우는 아래와 같이 정의될  있습니다.
            - [["eng_lower", "ABC"], ["digit"]] -> {길이 2, 영문-숫자 순으로 출력} -> recognition 결과 예시: "A0", "b1", "a8", "C0", ...
    "recognition.text_score_threshold": float,  # (default 0.5, 텍스트 인식 Score(Confidence), 인식된 텍스트에서 각 글자에 대한 확률을 평균낸 점수.)
    "params.batch_size": int,  # recognition에 한 번에 입력되는 이미지 개수 입니다.
                               # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
                               # (default 2)
    "params.max_num_of_text_objects": int,  # `infer_and_postprocess`에 한 번에 출력할 수 있는 최대 검출 개수 입니다.
                                             # <= 0 일 경우 최대 검출 수에 제한 없이 모든 텍스트를 검출합니다.
                                             # > 0 인 값을 지정하는 경우 해당 값 이하의 텍스트 수가 검출됩니다.
                                             # 이 때 detection 검출 후 detection confidence score 로 정렬하여, confidence score 가 높은 텍스트만을 검출합니다.
                                             # (default 0)
    "params.inspection_size_wh": Optional[List[int]],  # inference를 할 때, 내부 연산이 진행되는 image size 입니다.
                                                       # input image가 inspection_size_wh 넘는 경우 aspect ratio를 유지하며 resize 됩니다.
                                                       # input image가 inspection_size_wh 보다 작은 경우 부족한 부분을 zero padding으로 채웁니다.
                                                       # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
                                                       # (default None)
    "params.oversized_image_handling": str,  # inference시 inspection_size_wh 보다 큰 이미지에 대한 핸들링 옵션 입니다.
                                             # 아래 옵션들 중 한 가지를 선택할 수 있습니다.
                                             # "do_not_inspect" - 큰 이미지가 들어오면 에러 레이즈
                                             # "resize_to_fit" - 큰 이미지가 들어오면 inspection_size_wh 로 리사이즈해서 검사
                                             # (default "do_not_inspect")
}

사용 예시:

inferencer.get_default_inference_option(key="recognition.text_formatting")
inferencer.set_inference_option(key="recognition.text_formatting", value=["ABCDEF"])

Note

DetRecAnalyzer는 outputs.time을 제공하지 않습니다. (리턴에 time 없음)

get_inference_option(key)

현재 설정된 inference & postprocess 옵션 값을 읽습니다.

Parameters:

Name Type Description Default
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

get_default_inference_option과 동일합니다.

set_inference_option(key, value)

Inference & postprocess 옵션을 설정합니다.

Parameters:

Name Type Description Default
key str

설정하고자 하는 옵션 key 입니다.

required
value Any

설정하고자 하는 옵션 value 입니다.

required

Returns:

Name Type Description
None None

None

Keys

get_default_inference_option과 동일합니다.

Note1

DetRecAnalyzer에는 params.batch_size와 outputs.time 파라미터가 없습니다.

analyze(images, labeled)

저장된 network output으로 부터 images들에 대한 analysis 결과 계산

Args & Returns: DetRecInferencer.analyze()와 동일하며, 결과 predictions에서 time은 제외됩니다.

Note1

만약 ["params.inspection_size_wh", "params.batch_size", "params.oversized_image_handling"] 옵션이 변경되었을 경우 InferenceHandler.analyze를 호출하여 모델 인퍼런스를 재수행해야 합니다.

summarize_analysis(images, labeled)

images들에 대한 analysis summary 계산

Args & Returns: DetRecInferencer.summarize_analysis()와 동일.