Inference
cycle_counter.CycleCounterInferenceHandler
학습한 Video Classification 모델을 사용하여 검사할 프레임을 추출하기 위한 InferenceHandler 클래스입니다.
Usage
demo/demo_inference.py 참고
build(config)
classmethod
InferenceHandler 인스턴스를 생성합니다.
Parameters:
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가 존재하지 않습니다. 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가 존재하지 않습니다.
- 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), ...]
- average_distance: Optional[float] # 추적된 객체 중심 좌표가 다각형 중심에서부터의 평균 거리
- max_distance: Optional[float] # 추적된 객체 중심 좌표가 다각형 중심에서부터의 최대 거리
- within_score_ratio: 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), ...]
# "average_distance": Optional[float], # Average distance of tracked object centers from polygon centroids
# "max_distance": Optional[float], # Max distance of tracked object centers from polygon centroids
# "within_score_ratio": Optional[float], # Ratio of tracked points within polygon
# "path_template": Optional[dict[str, Any]], # Template info for path, {type: "polygon" or "polyline", points: list[tuple[int, int]]}
# },
# ...
# ]
get_default_inference_option(key)
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과 동일합니다.