2Facial emotions recognition implementation
5from __future__
import absolute_import, division, print_function
10from abc
import ABC, abstractmethod
11from typing
import List, Tuple, Union
17from .engagement_classification_model
import get_engagement_model
18from .utils
import get_model_path_onnx, get_model_path_torch
20FILE_DIR = pathlib.Path(__file__).parent.resolve()
24 from torchvision
import transforms
27 path_to_backbones = os.path.join(FILE_DIR,
"backbones")
28 if path_to_backbones
not in sys.path:
29 sys.path.append(path_to_backbones)
34 import onnxruntime
as ort
35 from onnx
import TensorProto, helper, numpy_helper
42 Returns a list of available model names.
44 These models are supported by HSEmoitonRecognizer.
47 List[str]: A list of model names.
50 "enet_b0_8_best_vgaf",
51 "enet_b0_8_best_afew",
62 Returns a list of supported inference engines.
65 List[str]: A list of inference engines.
67 return [
"torch",
"onnx"]
72 Abstract class for emotion recognizer classes
81 if "_7" in model_name:
103 if "mbf_" in model_name:
105 self.
std = [0.5, 0.5, 0.5]
108 self.
mean = [0.485, 0.456, 0.406]
109 self.
std = [0.229, 0.224, 0.225]
110 if "_b2_" in model_name:
112 elif "ddamfnet" in model_name:
122 Compute the final classification scores for the given feature representations.
125 features (np.ndarray): The extracted feature vectors.
128 np.ndarray: The raw classification scores (logits) before applying any activation
137 Prepare an image for input to the model.
140 img (np.ndarray): The input image for preprocessing.
143 np.ndarray: Preprocessed image.
145 raise NotImplementedError(
"It should be implemented")
150 Extract visual features from a facial image or a list of facial images.
153 face_img (Union[np.ndarray, List[np.ndarray]]):
154 A single face image (as a NumPy array) or a list of face images.
157 np.ndarray: The extracted feature vectors.
159 raise NotImplementedError(
"It should be implemented")
162 self, features: np.ndarray, logits: bool =
True
163 ) -> Tuple[List[str], np.ndarray]:
165 Classify emotions based on extracted feature representations.
168 features (np.ndarray): The extracted feature vectors.
169 logits (bool, optional):
170 If True, returns raw model scores (logits). If False, applies softmax normalization
171 to obtain probability distributions. Defaults to True.
174 Tuple[List[str], np.ndarray]:
175 - A list of predicted emotion labels.
176 - The corresponding model output scores (logits or probabilities), as a NumPy array.
183 preds = np.argmax(x, axis=1)
186 e_x = np.exp(x - np.max(x, axis=1)[:, np.newaxis])
187 e_x = e_x / e_x.sum(axis=1)[:,
None]
197 Classify engagement levels based on extracted feature representations using a sliding
201 features (np.ndarray): The extracted feature vectors from a video sequence.
202 sliding_window_width (int, optional):
203 The width of the sliding window used for engagement classification. Defaults to 128.
206 Tuple[List[str], np.ndarray]:
207 - A list of predicted engagement levels.
208 - The corresponding model output scores.
211 ValueError: If the number of frames in the video is smaller than the sliding window
215 if features.shape[0] < sliding_window_width:
217 f
"Not enough frames to predict engagement. "
218 f
"Sliding window width: {sliding_window_width}, "
219 f
"but number of frames in video: {features.shape[0]}"
221 max_iters = features.shape[0] - sliding_window_width
223 for i
in range(max_iters):
225 end = sliding_window_width + i
226 x = features[start:end]
227 mean_x = np.repeat(stat_func(x, axis=0).reshape((1, -1)), len(x), axis=0)
228 features_slices.append(np.concatenate((mean_x, x), axis=1))
229 features_slices = np.array(features_slices)
230 model = get_engagement_model(features_slices.shape[-1], sliding_window_width)
231 scores = model.predict(features_slices, verbose=0)
232 preds = np.argmax(scores, axis=1)
237 Predict the engagement presented on a sequence of facial images.
240 face_imgs (List[np.ndarray]):
241 A sequence of face images.
242 sliding_window_width (int, optional):
243 The width of the sliding window used for engagement classification. Defaults to 128.
246 Tuple[List[str], np.ndarray]:
247 - A list of predicted engagement levels.
248 - The corresponding model output scores.
251 ValueError: If the number of frames in the video is smaller than the sliding window
258 self, face_img: Union[np.ndarray, List[np.ndarray]], logits: bool =
True
259 ) -> Tuple[List[str], np.ndarray]:
261 Predict the emotions presented on a given facial image or a list of facial images.
264 face_img (Union[np.ndarray, List[np.ndarray]]):
265 A single face image (as a NumPy array) or a list of face images.
266 logits (bool, optional):
267 If True, returns raw model scores (logits). If False, applies softmax normalization
268 to obtain probability distributions. Defaults to True.
271 Tuple[Union[str, List[str]], np.ndarray]:
272 - The predicted emotion label(s) as a list of strings (for single image only with
274 - The corresponding model output scores (logits or probabilities), as a NumPy array.
282 Torch implementation of EmotiEffLibRecognizer.
285 def __init__(self, model_name: str =
"enet_b0_8_best_vgaf", device: str =
"cpu") ->
None:
289 path = get_model_path_torch(model_name)
291 model = torch.load(path, map_location=torch.device(
"cpu"), weights_only=
False)
293 model = torch.load(path, weights_only=
False)
294 if model_name ==
"mbf_va_mtl":
297 model.fc = torch.nn.Identity()
298 elif model_name ==
"mobilevit_va_mtl":
301 model.head.fc = torch.nn.Identity()
302 elif isinstance(model.classifier, torch.nn.Sequential):
305 model.classifier = torch.nn.Identity()
309 model.classifier = torch.nn.Identity()
311 model = model.to(device)
316 Prepare an image for input to the model.
319 img (np.ndarray): The input image for preprocessing.
322 np.ndarray: Preprocessed image.
324 test_transforms = transforms.Compose(
327 transforms.ToTensor(),
328 transforms.Normalize(mean=self.
mean, std=self.
std),
331 return test_transforms(Image.fromarray(img))
335 Extract visual features from a facial image or a list of facial images.
338 face_img (Union[np.ndarray, List[np.ndarray]]):
339 A single face image (as a NumPy array) or a list of face images.
342 np.ndarray: The extracted feature vectors.
344 if isinstance(face_img, np.ndarray):
346 img_tensor.unsqueeze_(0)
347 elif isinstance(face_img, list)
and all(isinstance(i, np.ndarray)
for i
in face_img):
348 img_tensor = [self.
_preprocess(img)
for img
in face_img]
349 img_tensor = torch.stack(img_tensor, dim=0)
351 raise TypeError(
"Expected np.ndarray or List[np.ndarray]")
353 features = features.data.cpu().numpy()
359 ONNX implementation of EmotiEffLibRecognizer.
362 def __init__(self, model_name: str =
"enet_b0_8_best_vgaf") ->
None:
365 path = get_model_path_onnx(model_name)
366 model = onnx.load(path)
369 gemm_node = nodes[-1]
370 new_output_name = gemm_node.input[0]
371 if gemm_node
is None or len(gemm_node.input) < 3:
372 raise RuntimeError(
"Unexpected gemm node!")
373 weight_name = gemm_node.input[1]
374 bias_name = gemm_node.input[2]
375 weight_tensor = next((t
for t
in graph.initializer
if t.name == weight_name),
None)
376 bias_tensor = next((t
for t
in graph.initializer
if t.name == bias_name),
None)
381 graph.node.remove(gemm_node)
382 graph.output.remove(graph.output[0])
384 new_output = helper.make_tensor_value_info(
385 new_output_name, TensorProto.FLOAT, new_output_shape
387 graph.output.append(new_output)
389 model_bytes = model.SerializeToString()
390 ort.set_default_logger_severity(3)
391 self.
ort_session = ort.InferenceSession(model_bytes, providers=[
"CPUExecutionProvider"])
395 Prepare an image for input to the model.
398 img (np.ndarray): The input image for preprocessing.
401 np.ndarray: Preprocessed image.
405 x[..., i] = (x[..., i] - self.
mean[i]) / self.
std[i]
406 return x.transpose(2, 0, 1).astype(
"float32")[np.newaxis, ...]
410 Extract visual features from a facial image or a list of facial images.
413 face_img (Union[np.ndarray, List[np.ndarray]]):
414 A single face image (as a NumPy array) or a list of face images.
417 np.ndarray: The extracted feature vectors.
419 if isinstance(face_img, np.ndarray):
421 elif isinstance(face_img, list)
and all(isinstance(i, np.ndarray)
for i
in face_img):
422 img_tensor = np.concatenate([self.
_preprocess(img)
for img
in face_img], axis=0)
424 raise TypeError(
"Expected np.ndarray or List[np.ndarray]")
425 features = self.
ort_session.run(
None, {
"input": img_tensor})[0]
431 engine: str =
"torch", model_name: str =
"enet_b0_8_best_vgaf", device: str =
"cpu"
432) -> Union[EmotiEffLibRecognizerOnnx, EmotiEffLibRecognizerTorch]:
434 Creates EmotiEffLibRecognizer instance.
437 engine (str): The engine to use for inference. Can be either "torch" or "onnx".
439 model_name (str): The name of the model to be used for emotion prediction.
440 Default is "enet_b0_8_best_vgaf".
441 device (str): The device on which to run the model, either "cpu" or "cuda".
445 EmotiEffLibRecognizerTorch or EmotiEffLibRecognizerOnnx: An instance of the corresponding
446 emotion recognition class based on the selected engine.
450 raise ValueError(
"Unsupported engine specified")
451 if engine ==
"torch":
454 from torchvision
import transforms
455 except ImportError
as e:
456 raise ImportError(
"Looks like torch module is not installed: ", e)
from e
461 import onnxruntime
as ort
462 from onnx
import helper, numpy_helper
463 except ImportError
as e:
464 raise ImportError(
"Looks like onnx module is not installed: ", e)
from e
Tuple[List[str], np.ndarray] predict_emotions(self, Union[np.ndarray, List[np.ndarray]] face_img, bool logits=True)
None __init__(self, str model_name)
np.ndarray _get_probab(self, np.ndarray features)
np.ndarray _preprocess(self, np.ndarray img)
np.ndarray extract_features(self, Union[np.ndarray, List[np.ndarray]] face_img)
dict idx_to_engagement_class
dict idx_to_emotion_class
Tuple[List[str], np.ndarray] classify_emotions(self, np.ndarray features, bool logits=True)
predict_engagement(self, List[np.ndarray] face_imgs, int sliding_window_width=128)
classify_engagement(self, np.ndarray features, int sliding_window_width=128)
np.ndarray _preprocess(self, np.ndarray img)
None __init__(self, str model_name="enet_b0_8_best_vgaf")
np.ndarray extract_features(self, Union[np.ndarray, List[np.ndarray]] face_img)
None __init__(self, str model_name="enet_b0_8_best_vgaf", str device="cpu")
np.ndarray extract_features(self, Union[np.ndarray, List[np.ndarray]] face_img)
np.ndarray _preprocess(self, np.ndarray img)
Union[EmotiEffLibRecognizerOnnx, EmotiEffLibRecognizerTorch] EmotiEffLibRecognizer(str engine="torch", str model_name="enet_b0_8_best_vgaf", str device="cpu")
List[str] get_supported_engines()
List[str] get_model_list()