콘텐츠로 이동

Task2: 시방준수

ktt.module.install_compliance.Inferencer

랜케이블 커넥터의 연결 상태 및 결함을 검출하고 시방준수 상태를 평가하는 파이프라인을 제공합니다.

주요 기능
  • RJ45 커넥터 자동 탐지
  • 디바이스 연결 상태 분류 (연결됨/연결 안됨)
  • 케이블 결함 검출 (정상/결함 있음)
  • 시방준수 상태 평가 및 보고
Usage

demo/demo_install_compliance_inference.py 참고


build(config) classmethod

API 인스턴스를 생성합니다.

Parameters:

Name Type Description Default
config dict

핸들러 빌드를 위한 설정 딕셔너리입니다.

{
    "detection": {
        "checkpoint_path": str,             # DET 모델 체크포인트 경로
        "password": str,                    # 체크포인트 암호
        "inference_options": dict | None,   # DET 모델 인퍼런스 옵션. 기본값은 None.
        "batch_size": int,                  # 검사 배치 크기. 기본값은 16.
    },
    "classification": {
        "checkpoint_path": str,             # MLC 모델 체크포인트 경로
        "password": str,                    # 체크포인트 암호
        "batch_size": int,                  # 검사 배치 크기. 기본값은 64.
    },
    "device": Union[int, str, torch.device],# 실행 디바이스 (기본값: "cpu")
                                            # 0, 1, ... (GPU 번호) 또는 "cpu"
}

required

Returns:

Name Type Description
Inferencer Inferencer

빌드 완료된 시방준수 추론 핸들러 인스턴스.


infer(images)

입력 이미지들에 대해 시방준수 검사를 수행합니다.

2단계 파이프라인을 실행합니다: 1) RJ45 커넥터 객체 탐지 (DET) 2) 탐지된 영역의 디바이스 연결 상태 및 결함 분류 (MLC) 각 탐지된 객체는 패딩과 함께 크롭되어 개별적으로 분류됩니다.

Parameters:

Name Type Description Default
images list[ndarray]

입력 이미지 리스트 (RGB, shape: (H, W, 3)). 각 이미지는 numpy 배열이며 0-255 범위의 uint8 값을 가져야 합니다.

required

Returns:

Type Description
list[dict]

list[dict]: 각 입력 이미지에 대한 추론 결과 딕셔너리 리스트. 예시는 아래와 같습니다.

[
    {
        "box_scores": list[int],                         # 탐지된 케이블 커넥터들의 신뢰도 점수 (0-100). 탐지 임계값으로 필터링됨
        "boxes_xyxy": list[tuple[int, int, int, int]],   # 바운딩 박스 좌표 (x1, y1, x2, y2) 형식. 픽셀 단위
        "device_states": list[bool],                     # 각 탐지 객체의 디바이스 연결 상태. True=연결됨 (임계값 초과)
        "defect_flags": list[bool],                      # 각 탐지 객체의 결함 존재 여부. True=결함 탐지됨 (임계값 초과)
        "probs": list[np.ndarray],                       # 각 탐지 객체의 원시 분류 확률값 [device_prob, defect_prob] (0-100 스케일)
        "compliance_status_list": list[str],             # 탐지 객체 단위 상세 시방준수 분류
                                                         # "compliance", "no_connector_detected", "no_connector_inserted",
                                                         # "connector_defect_detected", "connector_at_image_edge"
        "compliance_violation_detected": bool,           # 이미지 단위의 시방준수 상태. True=시방위반 발견
        "time": dict[str, float],                        # 실행 시간 분석 정보 (밀리초 단위)
                                                         # "detection_time": 탐지 모델 수행 시간 (ms)
                                                         # "classification_time": 분류 모델 수행 시간 (ms)
                                                         # "postprocess_time": 후처리 수행 시간 (ms)
    },
    ...  # 추가 이미지들에 대한 결과
]

# 탐지 실패 시 기본값. 케이블 커넥터가 탐지되지 않은 경우 아래의 기본값을 반환합니다.
{
    "box_scores": [],
    "boxes_xyxy": [],
    "device_states": [],
    "defect_flags": [],
    "probs": [],
    "time": {"detection_time": 0.0, "classification_time": 0.0, "postprocess_time": 0.0}, # 시간은 측정될 수 있음.
    "compliance_violation_detected": True,
    "compliance_status_list": ["no_connector_detected"],
}

Note
  • 탐지 관련 필드들이 빈 리스트인 경우 케이블 커넥터가 탐지되지 않았음을 의미합니다.
  • 모든 타이밍 정보는 배치 처리로 인해 배치 내 이미지들에 균등 분배됩니다.
  • 리스트 필드들의 길이는 모두 동일하며, 각 인덱스는 동일한 탐지 객체를 참조합니다.
  • compliance_status_list의 각 요소별 의미:
    • "compliance": 디바이스가 정상적으로 연결되고 결함이 없는 상태 (적합)
    • "no_connector_detected": 이미지에서 케이블 커넥터가 전혀 탐지되지 않은 상태 (부적합)
    • "no_connector_inserted": 케이블은 탐지되었으나 디바이스가 연결되지 않은 상태 (부적합)
    • "connector_defect_detected": 디바이스는 연결되었으나 케이블에 결함이 발견된 상태 (부적합)
    • "connector_at_image_edge": 모든 탐지된 커넥터가 이미지 가장자리(5% 경계) 내에 위치한 상태 (부적합)
  • compliance_violation_detected 판정 규칙:
    • 커넥터가 하나도 탐지되지 않은 경우 → True
    • 모든 커넥터가 이미지 가장자리에 위치한 경우 → True
    • 모든 커넥터가 연결되지 않은 경우(no_connector_inserted만 존재) → True
    • 하나라도 결함이 있는 경우(connector_defect_detected 존재) → True
    • 그 외의 경우 → False

get_default_inference_option(model, key)

특정 추론 옵션의 기본값을 조회합니다.

Parameters:

Name Type Description Default
model str

"detection" 또는 "classification" 중 하나.

required
key str

옵션 key.

required

Returns:

Name Type Description
Any Any

옵션 value.

Keys

model: detection key: DET 모델 결과 후처리 파라미터. 가능한 key는 다음과 같습니다.

{
    "params.object_score_threshold": list[int],  # 각 클래스의 score threshold 값. 예측 box의 score가 threshold보다 작은 경우 필터링 됩니다.
                                                    # 각 값은 [0, 100] 범위의 정수. (default [50])
    "params.object_area_threshold": list[int],  # 각 클래스의 area threshold 값. 예측 box의 면적이 threshold보다 작은 경우 필터링 됩니다.
                                                # 각 값은 0 이상의 정수. (default [1000])
    "params.max_num_of_detected_objects": list[int],  # 각 클래스의 최대 예측 박스 개수. 예측 box의 개수가 이 값을 넘을 경우 score가 낮은 순으로 제거됩니다.
                                                        # 각 값은 -1 이상의 정수이며, 값이 -1인 경우 개수 필터링을 적용하지 않습니다. (default [-1])
}

model: classification key: MLC 모델 결과 후처리 파라미터. 가능한 key는 다음과 같습니다.

{
    "params.mlc_thresholds": dict[str, int],  # 각 라벨의 분류 임계값. 예측 확률이 threshold보다 작은 경우 False로 판정됩니다.
                                                # 각 값은 [0, 100] 범위의 정수. (default {"connector_inserted": 50, "defect": 50})
}

Raises:

Type Description
InferenceOptionKeyError

지정된 모델이나 키가 존재하지 않는 경우.

Usage
err, msg, option = handler.get_default_inference_option(model="detection", key="params.object_score_threshold")
print(option)

get_inference_option(model, key)

현재 설정된 추론 옵션 값을 조회합니다.

Parameters:

Name Type Description Default
model str

"detection" 또는 "classification" 중 하나.

required
key str

옵션 key.

required

Returns:

Name Type Description
Any Any

옵션 value.

Keys

get_default_inference_option과 동일합니다.

Raises:

Type Description
InferenceOptionKeyError

지정된 모델이나 키가 존재하지 않는 경우.


set_inference_option(model, key, value)

추론 옵션을 설정합니다.

Parameters:

Name Type Description Default
model str

"detection" 또는 "classification" 중 하나.

required
key str

설정할 옵션 키.

required
value Any

설정할 새로운 값.

required
Keys

get_default_inference_option과 동일합니다.

Raises:

Type Description
InferenceOptionKeyError

지정된 모델이나 키가 존재하지 않는 경우.

InferenceOptionValueError

값의 형식이 잘못되었거나 임계값이 유효 범위를 벗어난 경우.