콘텐츠로 이동

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 | None,        # detection 모델 체크포인트 경로 (default: None (사전학습모델 사용))
    "detection_batch_size": int,                    # detection 모델의 배치 사이즈 (default: 1)
    "detection_inference_options": dict | None,     # detection 모델의 인퍼런스 옵션 (default: None)

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

    "inference_options": dict | None,        # 전체 인퍼런스 옵션. 자세한 내용은 `Inferencer.get_default_inference_option` 참조 (default: None)
    "password": str | None,                  # detection, depth 모델 password (default: None)
    "device": Union[str, int, torch.device], # device (default: torch.device("cuda"))
}

required

Returns:

infer(images)

Cctv 높이 및 난공사 여부, 적합 여부 인퍼런스 메서드 Args: images (list[np.ndarray]): 입력 이미지 리스트 (RGB, shape: (H, W, 3), dtype: uint8)

Returns:

Type Description
list[dict]

list[dict]: 인퍼런스 결과 리스트. 각 딕셔너리는 다음과 같은 키-값 쌍을 가집니다.

{
    "non_compliance": list[str],  # 부적합 항목 리스트
    "infer_depth": bool,          # depth 추론 수행 여부 (timer 계산용)

    # 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)

    # 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,         # 난공사 여부
    "cctv_height": float | None,         # CCTV 대푯점과 지면 대응점 간의 거리 (단위: 미터)

    # Timer 정보 (enable_timer=True 인 경우에만 값이 존재)
    "time": {
        "preprocess": float,      # 전처리 시간 (단위: 밀리초)
        "detection": float,       # 검출 시간 (단위: 밀리초)
        "depth": float,           # 깊이 추론 시간 (단위: 밀리초)
        "postprocess": float,     # 후처리 시간 (단위: 밀리초)
    }
}

Notes

non_compliance에 등장하는 값: - Depth 추론이 수행되지 않은 경우 (infer_depth is False, cctv_height is None) - cctv_not_found: CCTV 미검출 - cctv_not_centered: 검출된 CCTV가 이미지 중앙에 위치하지 않음 - ladder_not_found: 사다리 미검출 - 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: 사다리가 이미지에 완전히 보이지 않음 (사다리 박스가 이미지 경계에 닿아있음)

warmup()

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

옵션 키

required

Returns:

Name Type Description
Any Any

기본 인퍼런스 옵션 값

사용 가능한 model 및 key 조합은 다음과 같습니다.

model: cctv_height key: 가능한 key는 다음과 같습니다.

{
    "outputs.time": bool, # 인퍼런스시 각 단계별 시간 출력 여부 (default: False)
    "params.cctv_side_ignore_ratio": float,  # CCTV 박스가 이미지 측면에 너무 가까이 있는 경우 무시하는 비율 (0.0 ~ 0.5, default: 0.1)
                                             # 예: 0.1인 경우, 이미지 너비의 좌우 10% 영역안에 속한 CCTV 박스는 무시됩니다.
    "params.cctv_height_meter_threshold": float,  # 난공사 CCTV 높이 기준 임계값 (단위: 미터, default: 3.0)
}

model: detection key: 가능한 key는 다음과 같습니다.

{
    "params.object_score_threshold": float,  # 객체 검출 신뢰도 임계값 (default: 0.1)
    "params.prefix_text": str,            # prefix 텍스트 (default: "a photo of a")
    "params.positive_texts": list[str],   # 검출하고자 하는 객체 텍스트 리스트 (default: ["security camera", "ladder"])
    "params.negative_texts": list[str],   # 과검 방지용 부정 텍스트 리스트 (default: ["fire extinguisher", "fire alarm",
                                          #      "ceiling sprinkler", "smoke detector", "ceiling light",
                                          #      "wall light", "vent", "tool box"])
}

model: depth key: 가능한 key는 다음과 같습니다.

{
    "params.max_depth": float,  # 최대 깊이 값 (default: 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)

Model에 따른 현재 설정된 postprocess 옵션 값을 읽습니다.

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, _ = handler.get_inference_option(model="cctv_height", key="outputs.time")
print(option)
# True or False

set_inference_option(model, key, value)

Model에 따른 postprocess 옵션 값을 설정합니다.

Parameters:

Name Type Description Default
model str

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

required
key str

옵션 key

required
value Any

옵션 value

required
Keys

get_default_inference_option과 동일합니다.

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