콘텐츠로 이동

Inference

safety.InferenceHandler

학습한 Object Detection/ Classification 모델을 사용하여 검사를 하기 위한 InferenceHandler class 입니다.

Usage

demo/inference.py 참고

build(config) classmethod

InferenceHandler class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

InferenceHandler를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "detection_checkpoint_path": str, # Detection 모델 체크포인트 경로
    "classification_checkpoint_path": str, # Classification 모델 체크포인트 경로
    "falldown_classification_checkpoint_path": str, # Falldown Classification 모델 체크포인트 경로
    "reidentification_checkpoint_path": str, # Reidentification 모델 체크포인트 경로
    "password": Optional[str],  # 체크포인트 패스워드 (default None)
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
    "use_scripting": bool,  # torch.jit.scripting 사용 여부 (default True)
}

required

Returns:

Name Type Description
InferenceHandler

build가 완료된 safety.InferenceHandler class의 instance를 반환합니다.

infer_and_postprocess(images, timestamp, data_buffer=None)

현재 설정된 inference 옵션을 바탕으로 inference를 수행합니다. Args: images (List[np.ndarray]): inference를 수행할 이미지들의 list timestamp (float): ms를 포함한 timestamp e.g.) 1693529787.934439 data_buffer (Optional[dict]): Tracker를 위해 전 frame의 detection 결과와 해당 동영상의 id list 정보를 담은 buffer (default None) Returns: Tuple[List[dict], dict]: inference 결과

(
    [
        {
            "detected_boxes": [
                {
                    "bounding_box": List[int], # [x, y, w, h]
                    "class_index": int, # 0: person, 1: fire, 2: smoke.
                    "score": int, # 0 ~ 100. 예측된 class의 score
                    "id": int, # tracking id
                    "alarm_type": Optional[str], # "no_helmet", "fire", "smoke", "fallen_person" or None
                    "classification": Dict[str, float], # 각 class에 대한 classification score,
                                                          현재 frame에서의 falldown score (falldown_score_per_frame),
                                                          현재까지의 falldown score들의 EMA  (falldown_score)
                },
            ],
            "time": { # inference에 소요된 시간을 담고있는 dictionary 입니다. (단위: ms)
                "detection_time": float, # detection에 소요된 시간
                "classification_time": float, # classification에 소요된 시간
                "classification_count": int, # classification이 수행된 횟수
                "falldown_classification_time": float, # falldown classification에 소요된 시간
                "tracker_time": float, # person tracker에 소요된 시간
        },
    ],
    {
        "detection_boxes_person: List[dict], # 추후에 사용 될 현재 frame의 person detection 결과를 저장합니다.
        "detection_boxes_fire: List[dict], # 추후에 사용 될 현재 frame의 fire detection 결과를 저장합니다.
        "detection_boxes_smoke: List[dict], # 추후에 사용 될 현재 frame의 smoke detection 결과를 저장합니다.
        "id_manager_person: List[int] # 해당 검사 동영상의 person id 관리를 위한 list 입니다.
        "id_manager_fire: List[int] # 해당 검사 동영상의 fire id 관리를 위한 list 입니다.
        "id_manager_smoke: List[int] # 해당 검사 동영상의 smoke id 관리를 위한 list 입니다.
    }
)
Usage:
# helmet을 착용한 person인 경우
predictions = {
    "bounding_box": [18, 353, 18, 55],
    "class_index": 0,
    "score": 82,
    "id": 0,
    "alarm_type": None,
    "classification": {
        "helmet": 0.98,
        "head": 1.0,
        "person": 0.99,
        "fire": 0.0,
        "smoke": 0.0,
        "falldown_score_per_frame": 0.2,
        "falldown_score": 0.1,
    },
}

# helmet을 착용하지 않은 person인 경우
predictions = {
    "bounding_box": [18, 353, 18, 55],
    "class_index": 0,
    "score": 82,
    "id": 0,
    "alarm_type": "no_helmet",
    "classification": {
        "helmet": 0.02,
        "head": 1.0,
        "person": 0.99,
        "fire": 0.0,
        "smoke": 0.0,
        "falldown_score_per_frame": 0.2,
        "falldown_score": 0.1,
    },
}

# 쓰러짐이 감지된 person인 경우
predictions = {
    "bounding_box": [18, 353, 18, 55],
    "class_index": 0,
    "score": 82,
    "id": 0,
    "alarm_type": "fallen_person",
    "classification": {
        "helmet": 0.02,
        "head": 1.0,
        "person": 0.99,
        "fire": 0.0,
        "smoke": 0.0,
        "falldown_score_per_frame": 0.99,
        "falldown_score": 0.9,
    },
}

# fire가 detection된 경우
predictions = {
    "bounding_box": [18, 353, 18, 55],
    "class_index": 2,
    "score": 82,
    "id": 0,
    "alarm_type": "fire",
    "classification": {
        "helmet": 0.02,
        "head": 0.0,
        "person": 0.0,
        "fire": 0.99,
        "smoke": 0.0,
    },
}

warmup()

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

get_default_inference_option(model, key)

Model별 Postprocess 옵션의 기본 설정 값을 반환합니다.

Parameters:

Name Type Description Default
model str

"classification", "detection", 또는 "safety"

required
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

사용 가능한 key와 value 목록: model: detection

{
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
    "params.object_score_threshold": List[int],  # 각 클래스의 score threshold 값. 예측 box의 score가 threshold보다 작은 경우 필터링 됩니다.
                                          # 각 값은 [0, 100] 범위의 정수. (default [30, ... , 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])
}
model: classification
{
    "outputs.class_activation_map": bool,  # (default True, output 중 class_activation_map 계산할 지 여부. True인 경우 계산)
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
    "params.additional_scores": List[Union[int, float]],  # scores_including_add를 계산할 때, scores_original에 더해지는 값입니다. 각 값은 [0, 100] 범위의 실수. (default [0.0, ... , 0.0])
    "params.batch_size": int,  # `infer_and_postprocess`에 한 번에 입력할 수 있는 최대 이미지 개수 입니다.
                               # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
                               # (default 1)
}
 ```
model: falldown_classification
```python
{
    "outputs.class_activation_map": bool,  # (default True, output 중 class_activation_map 계산할 지 여부. True인 경우 계산)
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
    "params.additional_scores": List[Union[int, float]],  # scores_including_add를 계산할 때, scores_original에 더해지는 값입니다. 각 값은 [0, 100] 범위의 실수. (default [0.0, ... , 0.0])
    "params.batch_size": int,  # `infer_and_postprocess`에 한 번에 입력할 수 있는 최대 이미지 개수 입니다.
                               # 파라미터가 변경되는 경우 해당 값으로 warmup을 수행합니다.
                               # (default 1)
}
model: safety
{
    "outputs.time": bool,  # (default False, 인퍼런스 시 각 요소에 걸린 시간 측정 여부. True인 경우 측정)
}

사용 예시:

error, _ = handler.get_default_inference_option(model="detection", key="outputs.detected_objects")
error, _ = handler.set_inference_option(model="detection", key="outputs.detected_objects", value=False)

get_inference_option(model, key)

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

Parameters:

Name Type Description Default
model str

"classification", "detection", "falldown_classification" 또는 "safety"

required
key str

옵션 key

required

Returns:

Name Type Description
Any Any

옵션 value

Keys

get_default_inference_option과 동일합니다.

set_inference_option(model, key, value)

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

Parameters:

Name Type Description Default
model str

"classification", "detection", "falldown_classification" 또는 "safety"

required
key str

설정하고자 하는 옵션 key 입니다.

required
value Any

설정하고자 하는 옵션 value 입니다.

required

Returns:

Name Type Description
None None

None

Keys

get_default_inference_option과 동일합니다.

set_helmet_threshold(value=0.1)

Helmet classification threshold를 설정합니다.

Parameters:

Name Type Description Default
value float

0.0 ~ 1.0 사이의 실수. 0에 가까울 수록 no helmet, 1에 가까울수록 yes helmet. (default 0.1)

0.1

Returns:

Name Type Description
None None

None

Usage
handler.set_helmet_threshold(value=0.9)

set_falldown_threshold(value=0.8)

Falldown decision threshold를 설정합니다.

Parameters:

Name Type Description Default
value float

falldown을 판단하는데 사용하는 기준 값. 0.0 ~ 1.0 사이의 실수. (default 0.8)

0.8

Returns:

Name Type Description
_type_ None

None

Usage
handler.set_falldown_threshold(value=0.8)