Skip to content

Inference

generation.Inferencer

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

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

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

# 인퍼런스 옵션 초기값 확인
inference_options = {
    "mask.smooth_mask": True, # 라벨에 값이 지정되지 않았을 경우 디폴트 값으로 사용되는 옵션
    "mask.assist_intensity": 50, # 라벨에 값이 지정되지 않았을 경우 디폴트 값으로 사용되는 옵션
    "outputs.time": False,
}
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, _ = 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}")

# 디벨로퍼: Generate 수행
for image_id, image_info in data.items():
    image_info["save_dir"] = os.path.join(DEMO_DIR, str(image_id))
    images = {image_id: image_info}

    error, results = inferencer.generate(images=images)
    assert error >= 0

# 디벨로퍼: Auto Generate 수행
auto_generate_options = {
    "smooth_mask": True,
    "assist_intensity": 50,
    "data_type": "object",
    "num_generate": {0: 1},
    "mask_generation_mode": {"assist": True, "mask_pool": False},
    "box_expand_ratio": 1.0,
    "max_count_per_image": 1,
}

error, results = inferencer.auto_generate(images=images, options=auto_generate_options)
assert error >= 0

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)
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
}

required

Returns:

Name Type Description
Inferencer

build가 완료된 generation.Inferencer 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 목록:

{
    "mask.smooth_mask": bool,  # (default False, mask assist 결과 smoothing 여부. 입력에 smooth_mask가 지정되지 않은 경우 이 옵션을 사용합니다.)
    "mask.assist_intensity": int,  # (default 100, mask assist 결과 적용 강도. 100인 경우 mask assist 결과를 그대로 적용. 0인 경우 mask assist 결과를 적용하지 않음. 입력에 assist_intensity가 지정되지 않은 경우 이 옵션을 사용합니다.)
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
}

사용 예시:

inferencer.get_default_inference_option(key="mask.smooth_mask")
inferencer.set_inference_option(key="mask.smooth_mask", value=True)

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

auto_generate(images, options, callback_function=None)

images들에 대한 auto generation 수행

Parameters:

Name Type Description Default
images Dict[str, Dict]

generation에 사용할 데이터 리스트.

{
    "{image_id}": {
        "path": str,  # 원본 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [  # 2가지 타입 지원: "bounding_box" + "bitmap" 타입 / "contours" 타입
            {  # "bounding_box" + "bitmap" 타입
                "class_index": int,  # class index (0: background)
                "bounding_box": List[int],  # [left, top, width, height]
                "bitmap": str,  # base64 encoded png image string (shape: (h_label, w_label))
            },
            {  # "contours" 타입
                "class_index": int,  # class index (0: background)
                "contours": [  # cv2 형식의 contours. 0번째 contour가 outer, 나머지는 모두 inner.
                    ndarray(int32, shape=(num_points_0, 1, 2)),
                    ndarray(int32, shape=(num_points_1, 1, 2)),
                    ndarray(int32, shape=(num_points_2, 1, 2)),
                    ...  # contour 개수 만큼 반복
                ],
            }, # existing label
            ...,  # times number of labels in the image
        ],
        "save_dir": str,  # 해당 이미지의 generation 결과 저장 directory
        "save_idx": int,  # 해당 이미지의 generation 결과 저장 index의 시작 값  # ~/save_dir/save_idx/
    },
    ...,  # times number of images
}

required
options Dict[str, Any]

auto generation에 사용할 옵션 리스트.

{
    "smooth_mask": bool,  # (default False, mask assist 결과 smoothing 여부)
    "assist_intensity": int,  # (default 100, mask assist 결과 적용 강도. 100인 경우 mask assist 결과를 그대로 적용. 0인 경우 mask assist 결과를 적용하지 않음)
    "data_type": str,  # "object" or "texture"
    "num_generate": Dict[int, int],  # {class_index: number of defects to be generated}
    "mask_generation_mode": Dict[str, bool], # {assist: bool, mask_pool: bool}, both cannot be False at the same time
        If "data_type" is "object", cannot use "mask_pool" mode (should be False).
        Possible combinations with "data_type" and "mask_generation_mode" are as follows:
            - "data_type": "object", "mask_generation_mode": {"assist": True, "mask_pool": False}
            - "data_type": "texture", "mask_generation_mode": {"assist": True, "mask_pool": True}
            - "data_type": "texture", "mask_generation_mode": {"assist": False, "mask_pool": True}
            - "data_type": "texture", "mask_generation_mode": {"assist": True, "mask_pool": False}
    "box_expand_ratio": float,  # box expand ratio. 1.0 means no expand.
    "max_count_per_image": int,  # maximum number of defects to be generated per image
}

required
callback_function Optional[Callable[[int], Any]]

auto generation 중간 결과를 받을 callback function (default None). None일 경우, callback function을 사용하지 않음.

None

Raises:

Type Description
InferenceOptionNameError

옵션 이름이 올바르지 않을 경우 발생하는 에러

InferenceInvalidOptionError

옵션 값이 올바르지 않을 경우 발생하는 에러

InferenceAutoModeTrialExeed

auto mode의 trial 횟수가 초과할 경우 발생하는 에러

Returns:

Name Type Description
Dict Dict[str, Dict]

Generation 결과

{
    "{image_id}": {
        "image": np.ndarray,
        "width": int,
        "height": int,
        "generated_labels": [
            {
                "label_id": int,
                "class_index": int,
                "bounding_box": [int, int, int, int],
                "bitmap": str,
                "disabled_label": bool,
            },
            ..., # 이미지 상의 생성된 결함 수만큼 반복
        ],
        "time": {
            "imread_time": float,
            "inference_time": float,
            "mask_inference_time": float,
            "defect_inference_time": float,
            "post_processing_time": float,
        }
        "save_dir":  # 생성된 이미지의 generation 결과 저장 directory
        "save_idx":  # 생성된 이미지의 generation 결과 저장 index, 주어진 save_idx부터 시작하는 int  # ~/save_dir/save_idx/
    },
    ..., # 생성된 이미지 개수만큼 반복
}

generate(images, save_intermediate_file=True)

images들에 대한 generation 수행

Parameters:

Name Type Description Default
images Dict[str, Dict]

generation에 사용할 데이터 리스트.

{
    "{image_id}": {
        "path": str,  # 원본 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [
            {  # "bounding_box" + "bitmap" 타입
                "class_index": int,  # class index (0: background)
                "bounding_box": List[int],  # [left, top, width, height]
                "bitmap": str,  # base64 encoded png image string (shape: (h_label, w_label))
            },
            {  # "contours" 타입
                "class_index": int,  # class index (0: background)
                "contours": [  # cv2 형식의 contours. 0번째 contour가 outer, 나머지는 모두 inner.
                    ndarray(int32, shape=(num_points_0, 1, 2)),
                    ndarray(int32, shape=(num_points_1, 1, 2)),
                    ndarray(int32, shape=(num_points_2, 1, 2)),
                    ...  # contour 개수 만큼 반복
                ],
            }, # existing label
            ...,  # times number of labels in the image
            {
                "mode": "manual",  # manual mode
                "assist": bool,  # mask refine assistant 여부
                "assist_intensity": int,  # mask refine assistant 강도
                "smooth_mask": bool,  # mask smoothing 여부
                "class_index": int,  # class index to be generated
                "bounding_box": [int, int, int, int],  # bounding box (seg label format)
                "bitmap": str,  # seg mask bitmap (seg label format)
            }, # user label for generation
            ...,  # times number of labels to generate in the image
        ],
        "save_dir": str,  # 해당 이미지의 generation 결과 저장 directory
        "save_idx": int,  # 해당 이미지의 generation 결과 저장 index  # ~/save_dir/save_idx/
    },
    ...,  # times number of images
}

required
save_intermediate_file bool

중간 파일 저장 여부 (default True). True일 경우, 동일 위치의 기존 파일을 덮어씌움.

True

Returns:

Name Type Description
Dict Dict

Generation 결과

{
    "{image_id}": {
        "image": np.ndarray,
        "width": int,
        "height": int,
        "generated_labels": [
            {
                "label_id": int,
                "class_index": int,
                "bounding_box": [int, int, int, int],
                "bitmap": str,
                "disabled_label": bool,
            },
            ..., # 이미지 상의 생성된 결함 수만큼 반복
        ],
        "time": {
            "imread_time": float,
            "inference_time": float,
            "mask_inference_time": float,
            "defect_inference_time": float,
            "post_processing_time": float,
        }
        "save_dir":  # 입력으로 넣어주었던 해당 이미지의 generation 결과 저장 directory
        "save_idx": int,  # 해당 이미지의 generation 결과 저장 index, 입력 그대로 반환
    },
    ..., # 입력으로 넣어준 이미지 개수만큼 반복
}

add_label_and_generate(images, save_intermediate_file=True)

images들에 대한 generation 수행, 같은 경로에 이미 라벨 생성 결과가 있을 경우 덧붙여 생성합니다.

입출력은 generate와 동일합니다.

update_label_and_generate(images, save_intermediate_file=True)

images들에 대한 generation 수행, images의 각 라벨에 배정된 label_id에 해당하는 기존 생성 결과 라벨을 업데이트합니다.

입출력은 generate와 동일하되, 라벨을 업데이트하기 위한 label_id 값을 labels 엘리먼트에 무조건 포함해야 합니다.

{
    "{image_id}": {
        "path": str,  # 원본 이미지 경로
        "width": int,  # image width
        "height": int,  # image height
        "labels": [
            {
                "label_id": int, # label id to be updated
                "class_index": int,  # class index (0: background)
                "contours": [  # cv2 형식의 contours. 0번째 contour가 outer, 나머지는 모두 inner.
                    ndarray(int32, shape=(num_points_0, 1, 2)),
                    ndarray(int32, shape=(num_points_1, 1, 2)),
                    ndarray(int32, shape=(num_points_2, 1, 2)),
                    ...  # contour 개수 만큼 반복
                ],
            }, # existing label
            ...
        ]
        ...
}

delete_label_and_generate(images, label_ids, save_intermediate_file=True)

첫 생성 이후 특정 label을 삭제하고 나머지 라벨을 사용해 generation 재수행

입력 중 images, save_intermediate_file 와 출력은 generate와 동일합니다.

Parameters:

Name Type Description Default
label_ids Dict[str, List[int]]

삭제할 label id 리스트

{
    "{image_id}": [label_id_0, label_id_1, ...],
    ...,  # times number of images
}

required

warmup()

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