Spaces:
Sleeping
Sleeping
| import cv2 | |
| import numpy as np | |
| import onnxruntime as ort | |
| class LivenessDetector: | |
| def __init__(self, model_path, device="cpu"): | |
| providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if device == "cuda" else ['CPUExecutionProvider'] | |
| self.session = ort.InferenceSession(model_path, providers=providers) | |
| self.input_name = self.session.get_inputs()[0].name | |
| print(f"[INFO] Model loaded dari {model_path} pada device {device}") | |
| def _get_kernel(self, height, width): | |
| kernel_size = (height + width) / 2 | |
| scale = 2.7 | |
| return int(kernel_size * scale) | |
| def predict(self, img, bbox): | |
| """ | |
| img: gambar full BGR | |
| bbox: boundix box [x1, y1, x2, y2] hasil dari RetinaFace() | |
| """ | |
| h_img, w_img, _ = img.shape | |
| x1, y1, x2, y2 = map(int, bbox) | |
| box_h = y2 - y1 | |
| box_w = x2 - x1 | |
| center_x = x1 + box_w // 2 | |
| center_y = y1 + box_h // 2 | |
| side = self._get_kernel(box_h, box_w) | |
| new_x1 = max(0, center_x - side // 2) | |
| new_y1 = max(0, center_y - side // 2) | |
| new_x2 = min(w_img, center_x + side // 2) | |
| new_y2 = min(h_img, center_y + side // 2) | |
| cropped = img[new_y1:new_y2, new_x1:new_x2] | |
| if cropped.size == 0: | |
| return False, 0.0 | |
| # prep yaitu resize ke 80x80 | |
| resized = cv2.resize(cropped, (80, 80)) | |
| # Convert ke Float32 & Transpose (HWC -> CHW) | |
| blob = resized.astype(np.float32) | |
| blob = np.transpose(blob, (2, 0, 1)) | |
| blob = np.expand_dims(blob, 0) | |
| result = self.session.run(None, {self.input_name: blob}) | |
| probs = self._softmax(result[0][0]) | |
| return probs | |
| def _softmax(self, x): | |
| e_x = np.exp(x - np.max(x)) | |
| return e_x / e_x.sum() |