콘텐츠로 이동

Task1: 난공사

ktt.module.cctv_height.Inferencer

CCTV 높이와 난공사 여부를 판단하고 사진의 적합성을 평가하는 파이프라인을 제공합니다.

주요 기능
  • CCTV 및 사다리 검출
  • CCTV 높이 추정
  • 난공사 여부 판단
  • 사진 적합성 평가
Usage

demo/demo_cctv_height_compliance_inference.py 참고


build(config) classmethod

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

Parameters:

Name Type Description Default
config dict

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

{
    # Detection 모델 설정
    "detection_checkpoint_path": str,        # Detection 모델 체크포인트 경로 (사전학습 모델 경로를 입력해야 합니다)
    "detection_batch_size": int,                    # Detection 배치 크기 (기본값: 1)
    "detection_inference_options": dict | None,     # Detection 인퍼런스 옵션 (기본값: None)

    # Segmentation 모델 설정
    "segmentation_checkpoint_path": str,      # Segmentation 모델 체크포인트 경로 (사전학습 모델 경로를 입력해야 합니다)

    # Depth 모델 설정
    "depth_checkpoint_path": str | None,            # Depth 모델 체크포인트 경로 (기본값: None, 사전학습 모델 사용)
    "depth_inference_options": dict | None,         # Depth 인퍼런스 옵션 (기본값: None)
                                                    # 자세한 내용은 `Inferencer.get_default_inference_option` 참조

    # 공통 설정
    "inference_options": dict | None,               # 전체 인퍼런스 옵션 (기본값: None)
                                                    # 자세한 내용은 `Inferencer.get_default_inference_option` 참조
    "password": str | None,                         # Detection, Depth 모델 암호 (기본값: None)
    "device": Union[str, int, torch.device],        # 실행 디바이스 (기본값: torch.device("cuda"))
                                                    # 0, 1, ... (GPU 번호) 또는 "cpu", "cuda" 등
}

required

Returns:

Name Type Description
Inferencer Inferencer

빌드 완료된 CCTV 높이 추론 핸들러 인스턴스.


infer(images)

입력 이미지들에 대해 CCTV 높이 및 난공사 판정을 수행합니다.

4단계 파이프라인을 실행합니다: 1) 전처리 (이미지 정규화 및 변환) 2) CCTV 및 사다리 객체 탐지 3) Depth 추정 및 CCTV 높이 계산 4) 난공사 여부 및 사진 적합성 평가

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]: 각 입력 이미지에 대한 추론 결과 딕셔너리 리스트. 예시는 아래와 같습니다.

[
    {
        "non_compliance": list[str],                    # 부적합 항목 리스트 (경고 포함)
                                                        # 예: ["cctv_not_found", "ladder_not_found"]
        "compliance_violation_detected": bool,          # 부적합 여부. True=부적합, False=적합
                                                        # INCOMPLETE_LADDER_VISIBILITY만 있는 경우 False (적합이지만 경고)
                                                        # 그 외 non_compliance 항목이 있으면 True (부적합)
        "infer_depth": bool,                            # Depth 추론 수행 여부 (타이머 계산용)

        # CCTV 및 사다리 검출 결과
        "cctv_box": tuple[int, int, int, int] | None,   # CCTV 바운딩 박스 (x1, y1, x2, y2). 픽셀 단위
        "cctv_score": float | None,                     # CCTV 검출 신뢰도 점수 (0-1)
        "ladder_box": tuple[int, int, int, int] | None, # 사다리 바운딩 박스 (x1, y1, x2, y2). 픽셀 단위
        "ladder_score": float | None,                   # 사다리 검출 신뢰도 점수 (0-1)
        "rung_point_pair": tuple[tuple[int, int], tuple[int, int]] | None,
                                                        # 인접 사다리 발판 점 쌍

        # CCTV 높이 추정 및 난공사 판정 결과 (Depth 추론이 수행된 경우에만 값 존재)
        "cctv_uv": tuple[int, int] | None,              # CCTV 대표점 (x, y) 좌표. 픽셀 단위
        "ground_uv": tuple[int, int] | None,            # 지면 대응점 (x, y) 좌표. 픽셀 단위
        "ground_mask": np.ndarray | None,               # 리사이즈된 지면 마스크 (디버그용)
        "is_hard_work": bool | None,                    # 난공사 여부. True=난공사
        "cctv_height_raw": float | None,                # 보정 전 CCTV 높이 (단위: 미터)
                                                        # CCTV 대표점과 지면 대응점 간의 거리
        "cctv_height_calibrated": float | None,         # 보정 후 CCTV 높이 (단위: 미터)
        "calibration_factor": float,                    # 보정 계수 (1.0 = 보정 미적용)
        "measured_rung_distance": float | None,         # 측정된 사다리 발판 간격 (단위: 미터)

        # 타이밍 정보 (enable_timer=True인 경우에만 값 존재)
        "time": dict[str, float],                       # 각 단계별 소요 시간 (밀리초 단위)
            # "preprocess_time": 전처리 수행 시간 (ms)
            # "detection_time": 검출 수행 시간 (ms)
            # "segmentation_time": 세그멘테이션 수행 시간 (ms)
            # "depth_time": Depth 추론 수행 시간 (ms)
            # "postprocess_time": 후처리 수행 시간 (ms)
    },
    ...  # 추가 이미지들에 대한 결과
]

Notes: non_compliance에 등장하는 값: - Depth 추론이 수행되지 않은 경우 (infer_depth is False, cctv_height is None) - cctv_not_found: CCTV 미검출 → 부적합 - cctv_not_centered: 검출된 CCTV가 이미지 중앙에 위치하지 않음 → 부적합 - ladder_not_found: 사다리 미검출 → 부적합 - ladder_not_centered: 검출된 사다리가 이미지 중앙에 위치하지 않음 → 부적합 - Depth 추론이 수행되나, cctv_height 추정은 안되는 경우 (infer_depth is True, cctv_height is None) - cctv_point_not_found: CCTV 대푯점 검출 실패 → 부적합 - ladder_point_not_on_ground: 사다리가 지면 위에 존재하지 않음 (사다리 박스의 밑변 중 어떤 픽셀도 지면 마스크에 포함되지 않음) → 부적합 - ground_not_found: 지면 검출 실패 → 부적합 - ground_point_not_found: CCTV 연직 하방의 지면 대응점 검출 실패 → 부적합 - cctv_height 추정까지 성공하지만, 오차가 클 위험이 있는 경우 - incomplete_ladder_visibility: 사다리가 이미지에 완전히 보이지 않음 (사다리 박스가 이미지 경계에 닿아있음) → 적합 (경고) - incomplete_rung_visibility: 사다리 발판이 검출되지 않아 보정이 불가능함 → 적합 (경고)

compliance_violation_detected 판정 로직:
- non_compliance가 비어있는 경우 → False (완전 적합)
- non_compliance에 'incomplete_ladder_visibility' 또는 'incomplete_rung_visibility'만 있는 경우 → False (적합하지만 경고)
- 그 외 non_compliance 항목이 하나라도 있는 경우 → True (부적합)

warmup()

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

Warmup은 현재 inference_option이 잘 동작하는지 확인하고, GPU를 사용할 때 첫 호출 시 느린 속도 문제를 해결하기 위해 더미 입력에 대한 Inferencer.infer를 호출합니다.

Usage
handler.warmup()

get_default_inference_option(model, key)

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

Parameters:

Name Type Description Default
model str

"detection", "depth", "cctv_height" 중 하나.

required
key str

옵션 key.

required

Returns:

Name Type Description
Any Any

옵션 value.

Keys

사용 가능한 model 및 key 조합:

model: cctv_height

{
    "outputs.time": bool,                       # 인퍼런스 시 각 단계별 시간 출력 여부 (기본값: False)
    "params.side_ignore_ratio": float,         # CCTV/사다리 박스가 이미지 가장자리에 너무 가까이 있는 경우 무시하는 비율
                                                # 0.0 ~ 0.5 범위 (기본값: 0.1)
                                                # CCTV: 좌우 10% 영역, 하단 10% 영역
                                                # 사다리: 하단 5% 영역 (비율의 0.5배)
    "params.cctv_height_meter_threshold": float, # 난공사 CCTV 높이 기준 임계값 (단위: 미터, 기본값: 3.0)
}

model: detection

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

model: depth

{
    "params.max_depth": float,  # 최대 깊이 값 (기본값: 100.0, 단위: 미터)
}

Usage
err, msg, option = handler.get_default_inference_option(model="cctv_height", key="outputs.time")
print(option)  # False

get_inference_option(model, key)

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

Parameters:

Name Type Description Default
model str

"detection", "depth", "cctv_height" 중 하나.

required
key str

옵션 key.

required

Returns:

Name Type Description
Any Any

옵션 value.

Keys

get_default_inference_option과 동일합니다.

Usage
err, msg, option = handler.get_inference_option(model="cctv_height", key="outputs.time")
print(option)

set_inference_option(model, key, value)

추론 옵션을 설정합니다.

Parameters:

Name Type Description Default
model str

"detection", "depth", "cctv_height" 중 하나.

required
key str

옵션 key.

required
value Any

설정할 새로운 값.

required
Keys

get_default_inference_option과 동일합니다.

Note

설정 변경은 즉시 적용되며 다음 추론부터 새로운 값이 사용됩니다.

Usage
err, msg, _ = handler.set_inference_option(model="cctv_height", key="outputs.time", value=True)