콘텐츠로 이동

Task3: 침입관제

ktt.module.intrusion_monitoring.Inferencer

영상 침입 모니터링 시스템을 위한 추론 파이프라인을 제공합니다.

주요 기능
  • 비디오 클립에서 움직임 탐지 및 분석
  • 프레임별 모션 점수 계산 및 히트맵 생성
  • 최대 모션 프레임 추출 및 시각화
  • 객체 탐지 기반 침입 확인 (미구현)
Usage

demo/demo_intrusion_monitoring_inference.py 참고


build(config) classmethod

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

Parameters:

Name Type Description Default
config dict

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

{
    # 전처리 설정
    "preprocess": {
        "motion_resize": tuple[int, int],    # 모션 감지용 리사이즈 (W, H). 기본값: (320, 180)
        "detection_resize": tuple[int, int], # 객체 탐지용 리사이즈 (W, H). 기본값: (640, 360)
        "max_frames": int,                   # 비디오당 최대 프레임 수. 기본값: 150
        "sampling_stride": int,              # 프레임 샘플링 간격. 기본값: 1 (모든 프레임 사용)
        "num_workers": int,                  # 병렬 로딩 워커 수. 기본값: 4
    },
    # 모션 감지 설정
    "motion_detection": {
        "diff_thresh": float,           # 프레임 차이 임계값 (0-1 정규화). 기본값: 25.0/255.0
        "use_morphology": bool,         # 형태학적 연산 사용 여부. 기본값: True
        "topk_ratio": float,            # 상위 K 비율로 비디오 점수 집계. 기본값: 0.2
        "batch_shape": tuple[int, int], # 배치 처리 shape (H, W). 기본값: None (입력 크기 유지)
    },
    # 객체 탐지 설정
    "detection": {
        "checkpoint_path": str,              # 객체 탐지 모델 체크포인트 경로.
        "password": str | None,                # 체크포인트 암호 (필요한 경우).
        "optimize": bool,                   # 최적화된 모델 사용 여부. 기본값: False
        "batch_size": int,                  # 추론 배치 크기. 기본값: 32
        "inference_options": dict,          # 모델별 추론 옵션 딕셔너리.
            "params.object_score_threshold": list[int],  # 각 클래스의 score threshold 값.
            "params.object_area_threshold": list[int],   # 각 클래스의 area threshold 값.
            "params.max_num_of_detected_objects": list[int], # 각 클래스의 최대 예측 박스 개수.
    },
    "motion_threshold": float,               # 침입 판정 모션 임계값 (0-1). 기본값: 0.001
    "device": str,                           # 실행 디바이스. 기본값: "cpu"
                                             # "cpu", "cuda", "cuda:0" 등
}

required

Returns:

Name Type Description
Inferencer Inferencer

빌드 완료된 침입 모니터링 추론 핸들러 인스턴스.


infer(video_paths, surveillance_mode)

입력 비디오 클립들에 대해 침입 모니터링 추론을 수행합니다.

4단계 파이프라인을 실행합니다: 1) 비디오 로딩 및 전처리 (리사이징, 정규화) 2) 프레임 차이 기반 모션 감지 3) 모션 임계값 초과 시 객체 탐지 (미구현) 4) 결과 후처리 및 시각화 데이터 생성

Parameters:

Name Type Description Default
video_paths list[str]

입력 비디오 파일 경로 리스트. 각 경로는 절대 경로 또는 상대 경로 문자열이어야 합니다.

required
surveillance_mode bool

경계 모드 활성화 여부. True로 설정 시 침입자(사람) 탐지 알람이 활성화됩니다.

required

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: 각 입력 비디오에 대한 추론 결과 딕셔너리 리스트. 예시는 아래와 같습니다.

[
    {
        "index": int,                                   # 배치 내 비디오 인덱스 (0부터 시작)
        "video_path": str,                              # 비디오 파일 경로
        "video_score": float,                           # 비디오 전체 모션 점수 (0-1)
                                                        # topk_ratio로 집계된 대표 점수
        "motion_heatmap": np.ndarray,                   # 누적 모션 히트맵, shape (H, W)
                                                        # 값 범위: 0-1, 높을수록 모션 많음
        "frame_scores": dict[int, float],               # 실제 프레임 인덱스 → 모션 점수 매핑
                                                        # 프레임 i의 점수 = frame i와 frame i+1의 차이
                                                        # sampling_stride 고려한 실제 프레임 번호 사용
        "best_frame_timestamp": float,                  # 최대 모션 프레임의 타임스탬프 (초 단위)
                                                        # frame_index / fps로 계산됨
        "best_frame_score": float,                      # 최대 모션 프레임의 점수
        "best_frame_overlay": np.ndarray,               # 최대 모션 프레임 오버레이 시각화
                                                        # 원본 영상 해상도, RGB uint8
                                                        # 그레이스케일 + JET colormap 블렌딩
        "detection": dict[int, dict] | None,            # 객체 탐지 결과 (있는 경우)
            # None이면 탐지가 수행되지 않았음 (video_score < motion_threshold)
            # 비어있지 않으면, 프레임별 탐지 결과 매핑:
            # {
            #     frame_idx: {
            #         "class_index": list[int],         # 클래스 인덱스 리스트 (0: person, 1: fire)
            #         "box_scores": list[float],        # 신뢰도 점수 리스트 (0-100)
            #         "boxes_xyxy": list[list[int]],    # bbox 좌표 [x1, y1, x2, y2]
            #                                           # 원본 해상도 기준, 정수형
            #     },
            #     ...
            # },
        "alarm_info": dict[str, Any],                   # 알람 정보 딕셔너리
            "surveillance_mode": bool,                   # 침입 알람 활성화 여부 (default: False)
            "intrusion_detected": bool,                 # 침입 감지 여부
            "fire_detected": bool,                      # 화재 감지 여부
        "time": dict[str, float],                       # 각 단계별 소요 시간 (초)
    },
    ...  # 추가 비디오들에 대한 결과
]

Note
  • video_score는 topk로 집계된 대표 점수입니다.
  • best_frame_score는 영상 내 최대 모션 프레임의 점수입니다.
  • video_score가 motion_threshold를 초과하는 비디오만 객체 탐지를 수행합니다.
  • frame_scores는 실제 프레임 인덱스를 키로 사용합니다 (sampling_stride 고려).
  • best_frame_timestamp는 초 단위 타임스탬프입니다 (frame_index / fps로 계산).
  • motion_heatmap은 모든 프레임의 모션을 누적한 결과로, 모션이 빈번한 영역을 파악할 수 있습니다.
  • detection이 None이면 객체 탐지가 수행되지 않았음을 의미합니다.
  • detection이 빈 dict {}이면 탐지는 수행되었으나 아무것도 탐지되지 않았음을 의미합니다.
  • detection의 boxes_xyxy는 원본 비디오 해상도 기준으로 변환 완료되어 있습니다.
  • detection의 키는 실제 프레임 인덱스를 사용합니다 (sampling_stride 고려).
  • detection의 각 프레임별 리스트 필드들의 길이는 모두 동일하며, 각 인덱스는 동일한 탐지 객체를 참조합니다.
  • 최종 alarm은 alarm_info의 intrusion_detected 및 fire_detected 통해 확인할 수 있습니다.
  • surveillance_mode (경계 모드) 설정에 따른 알람 동작:
    • surveillance_mode=True: 침입 알람(intrusion_detected) 활성화
      • 사람(person) 객체가 감지되면 intrusion_detected=True로 설정됩니다.
      • 화재(fire) 알람은 surveillance_mode와 관계없이 항상 동작합니다.
    • surveillance_mode=False: 침입 알람 비활성화 (기본값)
      • 사람 객체가 감지되어도 intrusion_detected=False로 유지됩니다.
      • 화재 알람은 정상적으로 동작합니다 (fire_detected=True/False).
  • 화재 감지(fire_detected)는 surveillance_mode 설정과 무관하게 항상 활성화되어 있습니다.

Raises:

Type Description
ValueError

video_paths가 비어있는 경우.

RuntimeError

모든 비디오의 유효 프레임 수가 0인 경우.

FileNotFoundError

비디오 파일을 찾을 수 없는 경우.


get_default_inference_option(model, key)

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

Parameters:

Name Type Description Default
model str

"motion_detection", "detection" 중 하나.

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, 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])
}

Raises:

Type Description
InferenceOptionKeyError

지정된 키가 존재하지 않는 경우.

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

get_inference_option(model, key)

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

Parameters:

Name Type Description Default
model str

"motion_detection", "detection" 중 하나.

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

"motion_detection", "detection" 중 하나.

required
key str

옵션 key

required
value Any

설정할 새로운 값.

required
Keys

get_default_inference_option과 동일합니다.