Skip to content

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 입니다.

{
    # inference_handler config
    "detection_checkpoint_path": Optional[str], # Detection 모델 체크포인트 경로 (default None, None인 경우 default detection model 사용)
    "classification_checkpoint_path": Optional[str], # Classification 모델 체크포인트 경로 (default None, None인 경우 default classification model 사용)
    "reidentification_checkpoint_path": Optional[str], # Reidentification 모델 체크포인트 경로 (default None, None인 경우 default reidentification model 사용)
    "inference_batch_size": Optional[int], # Batch size 설정 (default 1)
    "password": Optional[str],  # 체크포인트 패스워드 (default None)
    "device": Union[int, str],  # GPU 번호 (int) or "cpu" (str) (default "cpu")
    "use_scripting": bool,  # torch.jit.scripting 사용 여부 (default True)

    # event_alarm_handlers config
    "camera_ids": Optional[list[int]], # 검사할 camera_id list. `InferenceHandler.register_camera`와 `InferenceHandler.release_camera`를 통해 camera_id를 등록/해제 할 수 있습니다.
}

required

Returns:

Name Type Description
InferenceHandler

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

Note
  1. "event_type_map"은 event_alarm 모듈에서 사용하는 event_type str과 api에서 사용하는 event_type str을 매핑하는 dictionary 입니다.
    • 백엔드에서는 사용하지 않으며, 연구소 내부적으로 사용하는 빌드 파라미터입니다.
  2. "detection_checkpoint_path", "classification_checkpoint_path", "reidentification_checkpoint_path"는 각 모델의 체크포인트 경로를 설정합니다.
    • None인 경우 해당 버전의 default 모델을 사용합니다.
  3. "detection"의 일부 인퍼런스 옵션이 기본으로 다음과 같이 세팅됩니다.
    {
        "params.object_score_threshold": [10] * n_detection_classes, # 각 detected_object의 score threshold 값. (범위: 0 ~ 100)
        "params.max_num_of_detected_objects": [30] + [-1] * (n_detection_classes - 1), # Person class의 최대 검출 개수는 30개로 제한.
    }
    

infer(images, camera_ids, timestamps)

현재 설정된 inference 옵션을 바탕으로 inference를 수행합니다. Args: images (list[np.ndarray]): inference를 수행할 이미지들의 list (shape: [H, W, C]) camera_ids (list[int]): images의 각 image에 대한 camera_id list timestamps (list[int]): images의 각 image에 대한 timestamp list (단위: 밀리초) Returns: list[dict]: 검사 결과

    [
        {
            "detected_objects": [ # 검출된 object들에 대한 정보 리스트
                {
                    "id": int, # object ID
                    "bounding_box": list[int], # object bounding box (x,y,w,h)
                    "object_class": str, # object의 class 이름. (Note 3 참고)
                    "object_score": int, # object의 det score. (범위: 0 ~ 100)
                    "classification_scores": {
                        "helmet": int,      # helmet class의 score. (범위: 0 ~ 100)
                        "head": int,        # head class의 score. (범위: 0 ~ 100)
                        "person": int,      # person class의 score. (범위: 0 ~ 100)
                        "fire": int,        # fire class의 score. (범위: 0 ~ 100)
                        "smoke": int,       # smoke class의 score. (범위: 0 ~ 100)
                        "fall_down": int,   # fall_down class의 score. (범위: 0 ~ 100)
                        "harness": int,     # harness class의 score. (범위: 0 ~ 100)
                    },
                    "events": { # object에 발생한 event에 대한 딕셔너리.
                        "without_helmet": bool,     # 헬멧 미착용 이벤트 (person object에 대해서만 해당)
                        "without_harness": bool,    # 하네스 미착용 이벤트 (person object에 대해서만 해당)
                        "fallen_person": bool,      # 쓰러짐 이벤트 (person object에 대해서만 해당)
                        "trespass_detect": bool,    # 침입 감지 이벤트 (person object에 대해서만 해당)
                        "danger_detect": bool,      # 배회 감지 이벤트 (person object에 대해서만 해당)
                        "collision_detect": bool,   # 협착 감지 이벤트 (person object에 대해서만 해당)
                        "fire_detect": bool,        # 화재 감지 이벤트 (fire object에 대해서만 해당)
                        "smoke_detect": bool,       # 연기 감지 이벤트 (smoke object에 대해서만 해당)
                    },
                    "alarms": { # object에 발생한 각 event에 대해서 alarm 여부 딕셔너리.
                        "without_helmet": bool,     # 헬멧 미착용 이벤트 (person object에 대해서만 해당)
                        "without_harness": bool,    # 하네스 미착용 이벤트 (person object에 대해서만 해당)
                        "fallen_person": bool,      # 쓰러짐 이벤트 (person object에 대해서만 해당)
                        "trespass_detect": bool,    # 침입 감지 이벤트 (person object에 대해서만 해당)
                        "danger_detect": bool,      # 배회 감지 이벤트 (person object에 대해서만 해당)
                        "collision_detect": bool,   # 협착 감지 이벤트 (person object에 대해서만 해당)
                        "fire_detect": bool,        # 화재 감지 이벤트 (fire object에 대해서만 해당)
                        "smoke_detect": bool,       # 연기 감지 이벤트 (smoke object에 대해서만 해당)
                    }
                }, ... # 각 image에서 검출된 object와 이에 대한 event, alarm 정보.
            ],
            "time": { # inference에 소요된 시간을 담고있는 dictionary 입니다. (단위: 밀리초)
                "detection_time": float, # detection에 소요된 시간
                "classification_time": float, # classification에 소요된 시간
                "classification_count": int, # classification이 수행된 횟수
                "tracker_time": float, # person tracker에 소요된 시간
            },
        }, ... # 들어온 image 수 만큼 반복 (들어온 image 순서대로)
    ]

warmup()

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

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: safety
```python
{
    "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" 또는 "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" 또는 "safety"

required
key str

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

required
value Any

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

required

Returns:

Name Type Description
None None

None

Keys

get_default_inference_option과 동일합니다.

register_camera(camera_id)

검사할 camera_id를 등록합니다.

Parameters:

Name Type Description Default
camera_id int

등록할 camera_id

required

Returns:

Name Type Description
None None

None

Raises:

Type Description
InvalidCameraIdError

camera_id가 int가 아닌 경우 발생하는 에러

AlreadyRegisteredCameraIdError

이미 등록된 camera_id를 등록하려고 할 때 발생하는 에러

release_camera(camera_id)

등록된 camera_id를 해제합니다.

Parameters:

Name Type Description Default
camera_id int

해제할 camera_id

required

Returns:

Name Type Description
None None

None

Raises:

Type Description
UnregisteredCameraIdError

등록되지 않은 camera_id를 해제하려고 할 때 발생하는 에러

get_registered_camera_ids()

등록된 camera_id 리스트를 반환합니다.

Returns:

Type Description
list[int]

list[int]: 등록된 camera_id 리스트

get_monitoring_area(camera_id)

등록된 camera_id에 대한 monitoring area를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

monitoring area를 반환할 camera_id

required

Returns:

Type Description
dict[str, list[list[tuple[int, int]]]]

Optional[list[list[tuple[int, int]]]]: monitoring area polygon list

{
    "includes": [ # 포함하는 영역의 폴리곤 리스트 (default [])
        [[x0, y0], [x1, y1], ..., [x0, y0]],
        [[x0, y0], [x1, y1], ..., [x0, y0]],
    ],
    "excludes": [ # 제외하는 영역의 폴리곤 리스트 (default [])
        [[x0, y0], [x1, y1], ..., [x0, y0]],
        [[x0, y0], [x1, y1], ..., [x0, y0]],
    ],
}

Raises: UnregisteredCameraIdError: 등록되지 않은 camera_id에 대한 정보를 요청할 때 발생하는 에러

set_monitoring_area(camera_id, monitoring_area)

등록된 camera_id에 대한 monitoring area를 설정합니다.

Parameters:

Name Type Description Default
camera_id int

monitoring area를 설정할 camera_id

required
monitoring_area dict[str, list[list[tuple[int, int]]]]

monitoring area polygon list 형태는 InferenceHandler.get_monitoring_area의 반환값과 동일합니다.

required

Returns:

Name Type Description
None None

None

Raises:

Type Description
InvalidMonitoringAreaError

monitoring_area가 올바르지 않을 때 발생하는 에러

UnregisteredCameraIdError

등록되지 않은 camera_id에 대해 설정할 때 발생하는 에러

get_default_object_options(camera_id)

등록된 camera_id에 대한 default object options를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

default object options를 반환할 camera_id

required

Returns:

Type Description
dict[str, dict]

dict[str, dict[str, Any]]: object options

{
    "person": {
        "enabled": bool,         # 해당 object_type을 검출할지 여부. 라이센스 조정을 위해 사용됩니다. (default True)
        "area_threshold": float, # 해당 object_type의 면적 threshold. 이 값보다 작은 object는 필터링 됩니다. (default 900.0)
        "score_threshold": int,  # 해당 object_type의 score threshold. 이 값보다 낮은 `object_score`를 가진 object는 필터링 됩니다. (default 30)
    },
    "fire": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 10
    },
    "smoke": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 10
    },
    "excavator": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
    "forklift": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
    "crane_body": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
    "crane_hook": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
    "crane_lifted_object": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
    "heavy_equipment": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
    "vehicle": {
        "enabled": bool,         # default True
        "area_threshold": float, # default 900.0
        "score_threshold": int,  # default 30
    },
}

Raises:

Type Description
UnregisteredCameraIdError

등록되지 않은 camera_id에 대한 정보를 요청할 때 발생하는 에러

get_object_options(camera_id)

등록된 camera_id에 대한 object options를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

object options를 반환할 camera_id

required

Returns:

Type Description
dict[str, dict]

dict[str, dict[str, Any]]: object options. 형태는 InferenceHandler.get_default_object_options의 반환값과 동일합니다.

Raises:

Type Description
UnregisteredCameraIdError

등록되지 않은 camera_id에 대한 정보를 요청할 때 발생하는 에러

set_object_options(camera_id, object_options)

등록된 camera_id에 대한 object options를 설정합니다.

Parameters:

Name Type Description Default
camera_id int

object options를 설정할 camera_id

required
object_options dict[str, dict]]

object options. 형태는 InferenceHandler.get_default_object_options의 반환값과 동일합니다.

required

Returns:

Name Type Description
None None

None

Raises:

Type Description
InvalidObjectOptionsError

object_options가 올바르지 않을 때 발생하는 에러

UnregisteredCameraIdError

등록되지 않은 camera_id에 대해 설정할 때 발생하는 에러

get_default_event_options(camera_id)

등록된 camera_id에 대한 default event options를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

default event options를 반환할 camera_id

required

Returns:

Type Description
dict[str, dict]

dict[str, dict[str, Any]]: event options python { "fire_detect": { "fire_score_threshold": int, # fire score threshold. 이 값보다 높은 fire score를 가진 object에 대해서만 이벤트를 발생시킵니다. (default 10) }, "smoke_detect": { "smoke_score_threshold": int, # smoke score threshold. 이 값보다 높은 smoke score를 가진 object에 대해서만 이벤트를 발생시킵니다. (default 10) }, "without_helmet": { "ignore_dark_object": bool, # 어두운 객체에 대한 이벤트를 무시할지 여부. (default True) "head_score_threshold": int, # head score threshold. 이 값보다 높은 head score를 가진 object에 대해서만 이벤트를 발생시킵니다. (default 90) "helmet_score_threshold": int, # helmet score threshold. 이 값보다 낮은 helmet score를 가진 object에 대해서만 이벤트를 발생시킵니다. (default 30) }, "without_harness": { "ignore_dark_object": bool, # 어두운 객체에 대한 이벤트를 무시할지 여부. (default True) "harness_score_threshold": int, # harness score threshold. 이 값보다 낮은 harness score를 가진 object에 대해서만 이벤트를 발생시킵니다. (default 30) }, "fallen_person": { "ignore_crossing_image_border_object": bool, # 이미지 경계를 넘어가는 객체에 대한 이벤트를 무시할지 여부. (default True) "ignore_dark_object": bool, # 어두운 객체에 대한 이벤트를 무시할지 여부. (default True) "fall_down_score_threshold": int, # fall_down score threshold. 이 값보다 높은 fall_down score를 가진 object에 대해서만 이벤트를 발생시킵니다. (default 70) }, "trespass_detect": { "area_ratio_threshold": int, # area_ratio_threshold. (default 95) # 이 값보다 높은 intersection area ratio (intersection_area / object_area) 를 가진 object에 대해서만 이벤트를 발생시킵니다. "polygons": list[list[tuple[int, int]]], # 침입 감지할 영역의 polygon list. (default [])python [ [[x0, y0], [x1, y1], ..., [x0, y0]], [[x0, y0], [x1, y1], ..., [x0, y0]], ] }, "danger_detect": { "area_ratio_threshold": int, # area_ratio_threshold. (default 95) # 이 값보다 높은 intersection area ratio (intersection_area / object_area) 를 가진 object에 대해서만 이벤트를 발생시킵니다. "polygons": list[list[tuple[int, int]]], # 배회 감지할 영역의 polygon list. (default [])python [ [[x0, y0], [x1, y1], ..., [x0, y0]], [[x0, y0], [x1, y1], ..., [x0, y0]], ] ``` } "collision_detect": { "area_ratio_threshold": int, # area_ratio_threshold. (default 50) # 이 값보다 높은 intersection area ratio (intersection_area / object_area) 를 가진 object에 대해서만 이벤트를 발생시킵니다. "center_y_offset_ratio": float, # 협착 위험 박스의 cy를 아래로 이동시키는 비율. (default 0.0) "width_scale": float, # 협착 위험 박스의 w를 늘리는 비율. (default 1.0) "height_scale": float, # 협착 위험 박스의 h를 늘리는 비율. (default 1.0) # 협착 위협 객체의 bounding box가 [c_x (박스 중심 x 좌표), c_y (박스 중심 y 좌표), w, h]일 때, # 협착 위험 박스는 [c_x, c_y + h * center_y_offset_ratio / 2, w * width_scale, h * height_scale] 으로 계산됩니다. }

get_event_options(camera_id)

등록된 camera_id에 대한 event options를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

event options를 반환할 camera_id

required

Returns:

Type Description
dict[str, dict]

dict[str, dict[str, Any]]: event options. 형태는 InferenceHandler.get_default_event_options의 반환값과 동일합니다.

Raises:

Type Description
UnregisteredCameraIdError

등록되지 않은 camera_id에 대한 정보를 요청할 때 발생하는 에러

set_event_options(camera_id, event_options)

등록된 camera_id에 대한 event options를 설정합니다.

Parameters:

Name Type Description Default
camera_id int

event options를 설정할 camera_id

required
event_options dict[str, dict]]

event options. 형태는 InferenceHandler.get_default_event_options의 반환값과 동일합니다.

required

Returns:

Name Type Description
None None

None

Raises:

Type Description
InvalidEventOptionsError

event_options가 올바르지 않을 때 발생하는 에러

UnregisteredCameraIdError

등록되지 않은 camera_id에 대해 설정할 때 발생하는 에러

get_default_alarm_options(camera_id)

등록된 camera_id에 대한 default alarm options를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

default alarm options를 반환할 camera_id

required

Returns:

Type Description
dict[str, dict]

dict[str, dict]: alarm options

{
    "fire_detect": {
        "start_time": int,              # 알람 활성화 시작 시각. 00:00:00 (단위: 초, default 0)
        "end_time": int,                # 알람 활성화 종료 시각. 23:59:59 (단위: 초, default 86399)
        "repeat_interval": int,         # 한번 울린 알람이 다시 울리기 까지 시간. (단위: 초, default 300)
        "alarm_interval": int,          # 해당 기간 동안 일정 비율 이상의 event가 발생해야 알람이 발생. (단위: 초, default 300)
        "alarm_ratio_threshold": int,   # alarm_interval 기간 동안 event가 발생한 비율이 이 값보다 크면 알람 발생. (단위: %, default 0)
    },
    "smoke_detect": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
    "without_helmet": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
    "without_harness": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
    "fallen_person": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
    "trespass_detect": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
    "danger_detect": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
    "collision_detect": {
        "start_time": int,
        "end_time": int,
        "repeat_interval": int,
        "alarm_interval": int,
        "alarm_ratio_threshold": int,
    },
}

Raises:

Type Description
UnregisteredCameraIdError

등록되지 않은 camera_id에 대한 정보를 요청할 때 발생하는 에러

get_alarm_options(camera_id)

등록된 camera_id에 대한 alarm options를 반환합니다.

Parameters:

Name Type Description Default
camera_id int

alarm options를 반환할 camera_id

required

Returns:

Type Description
dict[str, dict]

dict[str, dict]: alarm options. 형태는 InferenceHandler.get_default_alarm_options의 반환값과 동일합니다.

Raises:

Type Description
UnregisteredCameraIdError

등록되지 않은 camera_id에 대한 정보를 요청할 때 발생하는 에러

set_alarm_options(camera_id, alarm_options)

등록된 camera_id에 대한 alarm options를 설정합니다.

Parameters:

Name Type Description Default
camera_id int

alarm options를 설정할 camera_id

required
alarm_options dict[str, dict]]

alarm options. 형태는 InferenceHandler.get_default_alarm_options의 반환값과 동일합니다.

required

Returns:

Name Type Description
None None

None

Raises:

Type Description
InvalidAlarmOptionsError

alarm_options가 올바르지 않을 때 발생하는 에러

UnregisteredCameraIdError

등록되지 않은 camera_id에 대해 설정할 때 발생하는 에러

reset()

InferenceHandler의 상태를 초기화합니다.