Skip to content

Inference

rotated.InferenceHandler

학습한 Rotated Object Detection 모델을 사용하여 검사를 하기 위한 InferenceHandler 클래스입니다.

build(config) classmethod

InferenceHandler 클래스의 인스턴스를 생성합니다.

Parameters:

Name Type Description Default
config dict

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

{
    "checkpoint_path": str,  # 체크포인트 경로
    "inference_options": dict | None, # 인퍼런스 옵션 config (default None). 구조는 `get_default_inference_option`의 Keys 참고.
    "password": str | None,  # 체크포인트 패스워드 (default None)
    "device": torch.device | str | int,  # GPU 번호 (int) or "cpu" (str) (default torch.device("cpu"))
    "iou_threshold": float,  # Rotated IoU의 임계치. Metric 측정 시 실제 라벨과 추정 결과를 동일한 것으로 간주할 수 있는 두 박스이 겹치는 비율입니다. (default 0.8)
}

required

Returns:

Name Type Description
InferenceHandler InferenceHandler

빌드가 완료된 rotated.InferenceHandler 클래스의 인스턴스를 반환합니다.

get_default_inference_option(key)

inference_option의 기본 설정 값을 반환합니다.

Parameters:

Name Type Description Default
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys
{
    "outputs.time": bool,  # 인퍼런스 시간 측정 및 반환 여부. (default False)
    "params.batch_size": int,
        # `infer_and_postprocess`에 한 번에 입력할 수 있는 최대 이미지 개수 입니다. (default 1)
        # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
    "params.apply_nms": bool,
        # NMS를 적용할지 여부. (default True)
        # 적용하지 않을 경우, confidence threshold만 적용됩니다.
    "params.object_score_threshold": list[int],
        # 각 클래스의 score threshold 값. 예측 box의 score가 threshold보다 작은 경우 필터링 됩니다.
        # 각 값은 [0, 100] 범위의 정수. (default [30, ... , 30])
    "params.object_area_threshold": list[int],
        # 각 클래스의 area threshold 값. 예측 box의 면적이 threshold보다 작은 경우 필터링 됩니다.
        # 각 값은 0 이상의 정수. (default [0, ... , 0])
    "params.max_num_of_detected_objects": list[int],
        # 각 클래스의 최대 예측 박스 개수. 예측 box의 개수가 이 값을 넘을 경우 score가 낮은 순으로 제거됩니다.
        # 각 값은 -1 이상의 정수이며, 값이 -1인 경우 개수 필터링을 적용하지 않습니다. (default [-1, ... , -1])
}
Usage
handler.get_default_inference_option(key="params.object_score_threshold")

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과 동일합니다.

Usage
handler.get_inference_option(key="params.object_score_threshold")

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과 동일합니다.

Usage
handler.set_inference_option(key="params.object_score_threshold", value=[50])

infer_and_postprocess(images)

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

Parameters:

Name Type Description Default
images list[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]

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

[
    {  # 아래 키들 중 inference_options에 설정된 출력 값(outputs)들만 포함.
        "detected_objects: [  # list[dict], 설정된 object_score_threshold, object_area_threshold, max_num_of_detected_objects 의해 필터된 예측 bbox 리스트
            {
                "bounding_rot_box": list[float],  # 예측된 bounding box의 coordinate, cxcywh_360 [center_x, center_y, width, height, radian]
                "class_index": int,  # 예측된 bounding box의 class index
                "score": int,  # 예측된 bounding box의 score
                "area": float,  # object의 면적.
            },
            # 박스 개수만큼 반복
        ]
        "time": {  # inference에 소요된 시간을 담고있는 dictionary 입니다 (단위: ms). outputs.time가 True인 경우에만 존재.
            "imread_time": float,  # 실제 image를 load하여 연구팀이 사용하는 image format (numpy)으로 변경하기까지 걸리는 시간 (각 이미지 별로 걸리는 시간)
            "inference_time": float,  # resize, padding, tensorize, network forward 등을 포함하는 시간 (각 이미지 별로 걸리는 시간)
            "post_processing_time": float,  # postprocess에 걸린 시간 (각 이미지 별로 걸리는 시간)
        },
    },
    ...,  # 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,
        "height": int,
        "labels": [
            {
                "class_index": int,
                "bounding_rot_box": list[float],  # cxcywh_360 [center_x, center_y, width, height, radian]
            },
            ...,  # 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
                    "rotated_iou": float,  # label box에 대해 예측된 bounding box와 계산된 Rotated IoU 값
                },
                ... # 입력으로 넣어준 labels와 동일한 개수
        ],
        "predictions": {  # 아래 키들 중 inference_options에 설정된 출력 값들만 포함.
            "detected_objects: [  # list[dict]
                {
                    "bounding_rot_box": list[float],  # 예측된 bounding box의 coordinate, cxcywh_360 [center_x, center_y, width, height, radian]
                    "class_index": int,  # 예측된 bounding box의 class index
                    "score": int,  # 예측된 bounding box의 score
                    "rotated_iou": float,  # 예측 box에 대해 label box와 계산된 Rotated IoU 값
                    "correct": bool,  # True면 TP, False면 FP
                }
            ],
            "object/underkill": int,  # 현재 이미지의 label box 중 underkill 개수
            "object/overkill": int,  # 현재 이미지의 pred box 중 overkill 개수
            "time": {  # inference에 소요된 시간을 담고있는 dictionary 입니다. (단위: ms)
                "imread_time": float,  # 실제 image를 load하여 연구팀이 사용하는 image format (PIL)으로 변경하기까지 걸리는 시간 (각 이미지 별로 걸리는 시간)
                "inference_time": float,  # resize, roi, tensorize, network forward 등을 포함하는 시간 (각 이미지 별로 걸리는 시간)
                "post_processing_time": float,  # postprocess에 걸린 시간 (각 이미지 별로 걸리는 시간)
            },
        },
    },
    ... # 입력으로 넣어준 이미지 개수만큼 반복
},

Note1

analyze() 함수를 사용하기 위해서는 inference_options 중 outputs.detected_objects=True 여야 합니다.

Note2

모델 빌드 및 인퍼런스 없이 저장되어있는 network output을 활용하여 analyze하고 싶은 경우에는 AnalysisHandler.analyze()를 사용하세요.

warmup()

현재 설정된 inference 옵션을 바탕으로 warmup을 수행합니다. warmup은, 현재 inference_option이 잘 동작하는지 확인 + GPU를 첫 호출시 속도가 느린 이슈를 해결하기 위해, 현재 inference_option에 맞춰 더미 입력에 대한 InferenceHandler.infer_and_postprocess를 호출합니다.