콘텐츠로 이동

Inference

cycle_counter.CycleCounterInferenceHandler

학습한 Video Classification 모델을 사용하여 검사할 프레임을 추출하기 위한 InferenceHandler 클래스입니다.

Usage

demo/demo_inference.py 참고


build(config) classmethod

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

Parameters:

Name Type Description Default
config dict

InferenceHandler를 build 하기 위한 config가 담긴 dictionary 입니다.

{
    "model_name": str,  # 모델 이름
    "checkpoint_path": str,  # 체크포인트 경로
    "password": str,  # 체크포인트 패스워드
    "inference_options": Optional[Dict[str, Any]],  # 추론 옵션
    "device": Union[int, str],  # GPU 번호 (int) 또는 "cpu" (str) (기본값 "cpu")
    "anomaly_by_cycle_detector": Optional[dict],  # 주기 길이 이상치 검출 모델 설정
        ```python
        {
            "mode": str,  # 모드 (z-test, full_interval, marginal_interval)
            "stats": Optional[dict],  # 통계 정보 {class_id: {mean: float, sigma: float, sigma_level: float}, ...}
            "intervals": Optional[dict],  # 구간 정보 {class_id: {lower_full: float, upper_full: float}, ...}, {class_id: {lower_margin: float, upper_margin: float, base_time: float}, ...
        }
        ```
    "frame_selector": Optional[dict],  # 프레임 선택 모델 설정
        ```python
        {
            "cycle_select_offset_by_class": dict[str, list[int]],
                ```python
                {
                    "class_id": int,
                    "offset": list[int]
                }
                ```
        }
        ```
    "detection": Optional[dict],  # detection 엔진 설정
        ```python
        {
            "checkpoint_path": str,  # 체크포인트 경로
            "password": str,  # 체크포인트 패스워드
        }
        ```
    "det_template": Optional[dict],  # detection tracking 템플릿 설정
        ```python
        {
            "waypoints": dict[str, list[tuple[int, int]]],  # 템플릿 타입 (polygon, polyline)
            "phase_group_to_class": dict[str, int],  # [(class_name: class_index)]
            "class_to_phases": dict[int, list[str]],  # {class_index: [class_name,...]}
        }
        ```
    "tracked_anomaly_threshold": float,  # 경로 편차 이상치 판단 임계값 (기본값 50)
    "use_ts": bool,  # class segmentation에서 ms 기반의 ts 단위 사용 여부 (기본값 True)
}

required

Returns:

Name Type Description
InferenceHandler CycleCounterInferenceHandler

build가 완료된 cycle_counter.InferenceHandler 클래스의 인스턴스를 반환합니다.


infer(data, frame_timestamps)

주어진 데이터를 사용하여 추론을 수행합니다.

Parameters:

Name Type Description Default
data List[ndarray]

Inference에 사용할 데이터 입니다. 데이터는 (H, W, C) 형태와 RGB 채널의 numpy array 입니다.

required
frame_timestamps list[int]]

추론할 데이터에 대한 타임스탬프.

required

Returns:

Name Type Description
inference_status InferenceStatus

추론 상태를 반환합니다. InferenceStatus.SELECTED 이면, get_selected_frame을 호출하여 선택된 프레임을 가져올 수 있습니다.

inference_output list(InferenceOutput)

각 프레임에 대한 추론 결과를 반환합니다. list의 형태이며, 각 요소는 다음과 같은 키를 가집니다. - score (float) - class_index (int) - error (int) - cams (Optional[np.ndarray]) - probs (Optional[float]) - detection (Optional[dict]): detection 엔진 사용 시, 해당 프레임 timestamp에 매칭된 detection 결과. 단, detection 모델이 없는 경우 key가 존재하지 않습니다.

{
    "detected_objects": [{"bounding_box": [l,t,w,h], "class_index": int, "score": int}],
}
class 0 - white cell, class 1 - black cell, class 2 - robot arm head

InferenceStatus
  • INSPECT: 추론을 진행중이며, SELECT 과정에 있지 않습니다.
  • SELECTING: 현재 검사대상 구간이 존재하며, 검사후보를 선택 중입니다.
  • SELECTED: 검사후보를 선택했습니다.
  • ERROR: 추론 중 에러가 발생했습니다.
InferenceOutput
  • score (float): 추론 결과 검사후보의 점수입니다. (0.0 ~ 1.0)
  • class_index (int): 추론 결과의 클래스 인덱스입니다. (0 이면 검사대상이 아니며, 1 이면 검사후보 입니다.)
  • error (int): 에러 코드입니다. (0 이면 정상입니다.)
Usage
error, message, (inference_status, inference_output) = inference_handler.infer(data=sequence, timestamp=timestamp)

if inference_status == InferenceStatus.SELECTED:
    error, message, selected_frames = inference_handler.get_selected_frames()

# infer API에서 에러가 발생하는 경우, error==0, error_code=="Success"가 반환됩니다.
# 대신 inference_status가 InferenceStatus.ERROR로 설정되며, error code는 inference_output에서 확인할 수 있습니다.
# inference_output 각 요소의 값은 0.0, 0, error_code로 설정됩니다.
if inference_status == InferenceStatus.ERROR:
    error_code = inference_output[0]["error"]

get_cycles()

선택된 프레임들을 반환합니다.

Returns:

Type Description
list[CycleInfo]

list[CycleInfo]: 선택된 프레임 목록.

각 CycleInfo(dict)에는 다음과 같은 키가 포함됩니다:

Keys
  • class_index: int # 선택된 프레임의 클래스 인덱스
  • start_frame_ts: int # 선택된 프레임의 시작 타임스탬프
  • end_frame_ts: int # 선택된 프레임의 끝 타임스탬프
  • cycle_length: int # 선택된 프레임의 사이클 길이
  • original_class_index: Optional[int] = None # 선택된 프레임의 원본 클래스 인덱스
  • current_model: str
  • selected_frames: list[dict] # 이 사이클 내부에서 선택된 프레임들 (timestamp, offset, frame, score 등)
  • detections: Optional[dict[int, dict]] # 선택된 프레임들의 timestamp와 일치하는 detection 결과만 매핑하여 제공 (key: timestamp, value: detection dict). 단, detection 모델이 없는 경우 key가 존재하지 않습니다.
    {
        timestamp: {
            "detected_objects": [{"bounding_box": [l,t,w,h], "class_index": int, "score": int}],
        },
        ...
    }
    
  • last_frame: Optional[np.ndarray] # 선택된 프레임 중 마지막 프레임 (H, W, C) 형태와 RGB 채널의 numpy array
  • source: str # 이 CycleInfo가 생성된 경로 (예: None, 'det_only')
  • is_anomaly_by_cycle_length: bool # 주기 길이 이상치 여부
  • is_anomaly_by_vision: bool # 시각적 이상치 여부
  • is_anomaly_by_omitted_cell: bool # 셀 누락 이상치 여부
  • is_anomaly_by_tracked_coordinates: bool # 추적 좌표 이상치 여부

  • z_value: float # 주기 길이 이상치 검출 z 값

  • sigma: float # 주기 길이 이상치 검출 시그마 값
  • mean: float # 주기 길이 이상치 검출 평균 값
  • sigma_level: float # 주기 길이 이상치 검출 시그마 레벨

  • lower_time: Optional[int] # 이 사이클의 lower_time (있을 경우), 정상 사이클 판단 시간의 하한.

  • upper_time: Optional[int] # 이 사이클의 upper_time (있을 경우), 정상 사이클 판단 시간의 상한.

  • centers: Optional[List[Tuple[int, float, float]]] # 추적된 객체 중심 좌표 [(ts, x, y), ...]

  • distance: Optional[float] # 등록된 템플릿과 추적된 객체 중심 좌표 간의 거리
  • path_template: Optional[dict[str, Any]] # 경로 템플릿 정보 # {type: "polygon" or "polyline", points: list[tuple[int, int]]}
Usage
error, message, cycles = inference_handler.get_cycles()

print(cycles)
# [
#     {
#         "cycle_length": int,
#         "start_frame_ts": int,
#         "end_frame_ts": int,
#         "class_index": int,
#         "original_class_index": int,
#         "is_anomaly_by_cycle_length": bool,
#         "is_anomaly_by_vision": bool,
#         "is_anomaly_by_omitted_cell": bool,
#         "is_anomaly_by_tracked_coordinates": bool,
#         "z_value": Optional[float],
#         "sigma": Optional[float],
#         "mean": Optional[float],
#         "sigma_level": Optional[float],
#         "current_model": str,
#         "selected_frames": list[dict],
#             ```python
#             [
#                 {
#                     "offset": int,
#                     "frame": np.ndarray,
#                     "score": float,
#                     "timestamp": int,
#                     "anomaly_output": Optional[dict],
#                 }
#                 ...
#             ]
#             ```
#         "detections": Optional[dict[int, dict]]
#             ```python
#             {
#                 timestamp: {
#                     "detected_objects": [{"bounding_box": [l,t,w,h], "class_index": int, "score": int}],
#                 },
#                 ...
#             }
#             ```
#         "last_frame": Optional[np.ndarray],
#         "source": str,
#         "lower_time": Optional[int],
#         "upper_time": Optional[int],
#         "centers": Optional[List[Tuple[int, float, float]]],  # Tracked object centers [(ts, x, y), ...]
#         "distance": Optional[float],  # Distance of tracked object centers from template
#         "path_template": Optional[dict[str, Any]],  # Template info for path, {type: "polygon" or "polyline", points: list[tuple[int, int]]}
#     },
#     ...
# ]

get_default_inference_option(key)

inference 옵션의 기본 설정 값을 반환합니다.

Parameters:

Name Type Description Default
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

사용 가능한 key와 value 목록:

{
    "frame_selection_method": "class",  # 프레임 선택 방법
}


get_inference_option(key)

현재 설정된 inference 옵션 값을 읽습니다.

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 옵션을 설정합니다.

Parameters:

Name Type Description Default
key str

옵션 key

required
value Any

옵션 value

required
Keys

get_default_inference_option과 동일합니다.


reset()

InferenceHandler를 초기화합니다. 만약, 영상이 끊겼다가 들어올 경우 사용합니다.

Usage
inference_handler.reset()

set_anomaly_by_cycle_detector(config)

주기 길이 이상치 검출 모델을 설정합니다.

Parameters:

Name Type Description Default
config dict[str, Any]

주기 길이 이상치 검출 모델 설정

{
    "mode": str,  # 모드 (z-test)
    "stats": dict,  # 통계 정보 {class_id: {mean: float, sigma: float, sigma_level: float}, ...}
}

required

Returns:

Type Description
None

None