EmotiEffLib
Python implementation of Emotion Efficient Library
Loading...
Searching...
No Matches
facial_analysis.py
Go to the documentation of this file.
1"""
2Facial emotions recognition implementation
3"""
4
5from __future__ import absolute_import, division, print_function
6
7import os
8import pathlib
9import sys
10from abc import ABC, abstractmethod
11from typing import List, Tuple, Union
12
13import cv2
14import numpy as np
15from PIL import Image
16
17from .engagement_classification_model import get_engagement_model
18from .utils import get_model_path_onnx, get_model_path_torch
19
20FILE_DIR = pathlib.Path(__file__).parent.resolve()
21
22try:
23 import torch
24 from torchvision import transforms
25
26 # It is required for mbf_va_mtl
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)
30except ImportError:
31 pass
32try:
33 import onnx
34 import onnxruntime as ort
35 from onnx import TensorProto, helper, numpy_helper
36except ImportError:
37 pass
38
39
40def get_model_list() -> List[str]:
41 """
42 Returns a list of available model names.
43
44 These models are supported by HSEmoitonRecognizer.
45
46 Returns:
47 List[str]: A list of model names.
48 """
49 return [
50 "enet_b0_8_best_vgaf",
51 "enet_b0_8_best_afew",
52 "enet_b2_8",
53 "enet_b0_8_va_mtl",
54 "enet_b2_7",
55 "mbf_va_mtl",
56 "mobilevit_va_mtl",
57 ]
58
59
60def get_supported_engines() -> List[str]:
61 """
62 Returns a list of supported inference engines.
63
64 Returns:
65 List[str]: A list of inference engines.
66 """
67 return ["torch", "onnx"]
68
69
71 """
72 Abstract class for emotion recognizer classes
73 """
74
75 def __init__(self, model_name: str) -> None:
76 self.is_mtl = "_mtl" in model_name
78 0: "Distracted",
79 1: "Engaged",
80 }
81 if "_7" in model_name:
83 0: "Anger",
84 1: "Disgust",
85 2: "Fear",
86 3: "Happiness",
87 4: "Neutral",
88 5: "Sadness",
89 6: "Surprise",
90 }
91 else:
93 0: "Anger",
94 1: "Contempt",
95 2: "Disgust",
96 3: "Fear",
97 4: "Happiness",
98 5: "Neutral",
99 6: "Sadness",
100 7: "Surprise",
101 }
102
103 if "mbf_" in model_name:
104 self.mean = [0.5, 0.5, 0.5]
105 self.std = [0.5, 0.5, 0.5]
106 self.img_size = 112
107 else:
108 self.mean = [0.485, 0.456, 0.406]
109 self.std = [0.229, 0.224, 0.225]
110 if "_b2_" in model_name:
111 self.img_size = 260
112 elif "ddamfnet" in model_name:
113 self.img_size = 112
114 else:
115 self.img_size = 224
116
118 self.classifier_bias = None
119
120 def _get_probab(self, features: np.ndarray) -> np.ndarray:
121 """
122 Compute the final classification scores for the given feature representations.
123
124 Args:
125 features (np.ndarray): The extracted feature vectors.
126
127 Returns:
128 np.ndarray: The raw classification scores (logits) before applying any activation
129 function.
130 """
131 x = np.dot(features, np.transpose(self.classifier_weights)) + self.classifier_bias
132 return x
133
134 @abstractmethod
135 def _preprocess(self, img: np.ndarray) -> np.ndarray:
136 """
137 Prepare an image for input to the model.
138
139 Args:
140 img (np.ndarray): The input image for preprocessing.
141
142 Returns:
143 np.ndarray: Preprocessed image.
144 """
145 raise NotImplementedError("It should be implemented")
146
147 @abstractmethod
148 def extract_features(self, face_img: Union[np.ndarray, List[np.ndarray]]) -> np.ndarray:
149 """
150 Extract visual features from a facial image or a list of facial images.
151
152 Args:
153 face_img (Union[np.ndarray, List[np.ndarray]]):
154 A single face image (as a NumPy array) or a list of face images.
155
156 Returns:
157 np.ndarray: The extracted feature vectors.
158 """
159 raise NotImplementedError("It should be implemented")
160
162 self, features: np.ndarray, logits: bool = True
163 ) -> Tuple[List[str], np.ndarray]:
164 """
165 Classify emotions based on extracted feature representations.
166
167 Args:
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.
172
173 Returns:
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.
177 """
178 scores = self._get_probab(features)
179 if self.is_mtl:
180 x = scores[:, :-2]
181 else:
182 x = scores
183 preds = np.argmax(x, axis=1)
184
185 if not logits:
186 e_x = np.exp(x - np.max(x, axis=1)[:, np.newaxis])
187 e_x = e_x / e_x.sum(axis=1)[:, None]
188 if self.is_mtl:
189 scores[:, :-2] = e_x
190 else:
191 scores = e_x
192
193 return [self.idx_to_emotion_class[pred] for pred in preds], scores
194
195 def classify_engagement(self, features: np.ndarray, sliding_window_width: int = 128):
196 """
197 Classify engagement levels based on extracted feature representations using a sliding
198 window approach.
199
200 Args:
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.
204
205 Returns:
206 Tuple[List[str], np.ndarray]:
207 - A list of predicted engagement levels.
208 - The corresponding model output scores.
209
210 Raises:
211 ValueError: If the number of frames in the video is smaller than the sliding window
212 width.
213 """
214 stat_func = np.std
215 if features.shape[0] < sliding_window_width:
216 raise ValueError(
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]}"
220 )
221 max_iters = features.shape[0] - sliding_window_width
222 features_slices = []
223 for i in range(max_iters):
224 start = i
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)
233 return [self.idx_to_engagement_class[pred] for pred in preds], scores
234
235 def predict_engagement(self, face_imgs: List[np.ndarray], sliding_window_width: int = 128):
236 """
237 Predict the engagement presented on a sequence of facial images.
238
239 Args:
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.
244
245 Returns:
246 Tuple[List[str], np.ndarray]:
247 - A list of predicted engagement levels.
248 - The corresponding model output scores.
249
250 Raises:
251 ValueError: If the number of frames in the video is smaller than the sliding window
252 width.
253 """
254 features = self.extract_features(face_imgs)
255 return self.classify_engagement(features, sliding_window_width)
256
258 self, face_img: Union[np.ndarray, List[np.ndarray]], logits: bool = True
259 ) -> Tuple[List[str], np.ndarray]:
260 """
261 Predict the emotions presented on a given facial image or a list of facial images.
262
263 Args:
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.
269
270 Returns:
271 Tuple[Union[str, List[str]], np.ndarray]:
272 - The predicted emotion label(s) as a list of strings (for single image only with
273 one element).
274 - The corresponding model output scores (logits or probabilities), as a NumPy array.
275 """
276 features = self.extract_features(face_img)
277 return self.classify_emotions(features, logits)
278
279
281 """
282 Torch implementation of EmotiEffLibRecognizer.
283 """
284
285 def __init__(self, model_name: str = "enet_b0_8_best_vgaf", device: str = "cpu") -> None:
286 super().__init__(model_name)
287 self.device = device
288
289 path = get_model_path_torch(model_name)
290 if device == "cpu":
291 model = torch.load(path, map_location=torch.device("cpu"), weights_only=False)
292 else:
293 model = torch.load(path, weights_only=False)
294 if model_name == "mbf_va_mtl":
295 self.classifier_weights = model.fc.weight.cpu().data.numpy()
296 self.classifier_bias = model.fc.bias.cpu().data.numpy()
297 model.fc = torch.nn.Identity()
298 elif model_name == "mobilevit_va_mtl":
299 self.classifier_weights = model.head.fc.weight.cpu().data.numpy()
300 self.classifier_bias = model.head.fc.bias.cpu().data.numpy()
301 model.head.fc = torch.nn.Identity()
302 elif isinstance(model.classifier, torch.nn.Sequential):
303 self.classifier_weights = model.classifier[0].weight.cpu().data.numpy()
304 self.classifier_bias = model.classifier[0].bias.cpu().data.numpy()
305 model.classifier = torch.nn.Identity()
306 else:
307 self.classifier_weights = model.classifier.weight.cpu().data.numpy()
308 self.classifier_bias = model.classifier.bias.cpu().data.numpy()
309 model.classifier = torch.nn.Identity()
310
311 model = model.to(device)
312 self.model = model.eval()
313
314 def _preprocess(self, img: np.ndarray) -> np.ndarray:
315 """
316 Prepare an image for input to the model.
317
318 Args:
319 img (np.ndarray): The input image for preprocessing.
320
321 Returns:
322 np.ndarray: Preprocessed image.
323 """
324 test_transforms = transforms.Compose(
325 [
326 transforms.Resize((self.img_size, self.img_size)),
327 transforms.ToTensor(),
328 transforms.Normalize(mean=self.mean, std=self.std),
329 ]
330 )
331 return test_transforms(Image.fromarray(img))
332
333 def extract_features(self, face_img: Union[np.ndarray, List[np.ndarray]]) -> np.ndarray:
334 """
335 Extract visual features from a facial image or a list of facial images.
336
337 Args:
338 face_img (Union[np.ndarray, List[np.ndarray]]):
339 A single face image (as a NumPy array) or a list of face images.
340
341 Returns:
342 np.ndarray: The extracted feature vectors.
343 """
344 if isinstance(face_img, np.ndarray):
345 img_tensor = self._preprocess(face_img)
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)
350 else:
351 raise TypeError("Expected np.ndarray or List[np.ndarray]")
352 features = self.model(img_tensor.to(self.device))
353 features = features.data.cpu().numpy()
354 return features
355
356
358 """
359 ONNX implementation of EmotiEffLibRecognizer.
360 """
361
362 def __init__(self, model_name: str = "enet_b0_8_best_vgaf") -> None:
363 super().__init__(model_name)
364
365 path = get_model_path_onnx(model_name)
366 model = onnx.load(path)
367 graph = model.graph
368 nodes = graph.node
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)
377 self.classifier_weights = numpy_helper.to_array(weight_tensor) if weight_tensor else None
378 self.classifier_bias = numpy_helper.to_array(bias_tensor) if bias_tensor else None
379
380 # Remove the last node
381 graph.node.remove(gemm_node)
382 graph.output.remove(graph.output[0])
383 new_output_shape = [None, self.classifier_weights.shape[1]]
384 new_output = helper.make_tensor_value_info(
385 new_output_name, TensorProto.FLOAT, new_output_shape
386 )
387 graph.output.append(new_output)
388
389 model_bytes = model.SerializeToString()
390 ort.set_default_logger_severity(3)
391 self.ort_session = ort.InferenceSession(model_bytes, providers=["CPUExecutionProvider"])
392
393 def _preprocess(self, img: np.ndarray) -> np.ndarray:
394 """
395 Prepare an image for input to the model.
396
397 Args:
398 img (np.ndarray): The input image for preprocessing.
399
400 Returns:
401 np.ndarray: Preprocessed image.
402 """
403 x = cv2.resize(img, (self.img_size, self.img_size)) / 255
404 for i in range(3):
405 x[..., i] = (x[..., i] - self.mean[i]) / self.std[i]
406 return x.transpose(2, 0, 1).astype("float32")[np.newaxis, ...]
407
408 def extract_features(self, face_img: Union[np.ndarray, List[np.ndarray]]) -> np.ndarray:
409 """
410 Extract visual features from a facial image or a list of facial images.
411
412 Args:
413 face_img (Union[np.ndarray, List[np.ndarray]]):
414 A single face image (as a NumPy array) or a list of face images.
415
416 Returns:
417 np.ndarray: The extracted feature vectors.
418 """
419 if isinstance(face_img, np.ndarray):
420 img_tensor = self._preprocess(face_img)
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)
423 else:
424 raise TypeError("Expected np.ndarray or List[np.ndarray]")
425 features = self.ort_session.run(None, {"input": img_tensor})[0]
426 return features
427
428
429# pylint: disable=invalid-name
431 engine: str = "torch", model_name: str = "enet_b0_8_best_vgaf", device: str = "cpu"
432) -> Union[EmotiEffLibRecognizerOnnx, EmotiEffLibRecognizerTorch]:
433 """
434 Creates EmotiEffLibRecognizer instance.
435
436 Args:
437 engine (str): The engine to use for inference. Can be either "torch" or "onnx".
438 Default is "torch".
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".
442 Default is "cpu".
443
444 Returns:
445 EmotiEffLibRecognizerTorch or EmotiEffLibRecognizerOnnx: An instance of the corresponding
446 emotion recognition class based on the selected engine.
447 """
448 # pylint: disable=unused-import, import-outside-toplevel, redefined-outer-name
449 if engine not in get_supported_engines():
450 raise ValueError("Unsupported engine specified")
451 if engine == "torch":
452 try:
453 import torch
454 from torchvision import transforms
455 except ImportError as e:
456 raise ImportError("Looks like torch module is not installed: ", e) from e
457 return EmotiEffLibRecognizerTorch(model_name, device)
458 # ONNX
459 try:
460 import onnx
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
465 return EmotiEffLibRecognizerOnnx(model_name)
Tuple[List[str], np.ndarray] predict_emotions(self, Union[np.ndarray, List[np.ndarray]] face_img, bool logits=True)
np.ndarray _get_probab(self, np.ndarray features)
np.ndarray extract_features(self, Union[np.ndarray, List[np.ndarray]] face_img)
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)
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)
Union[EmotiEffLibRecognizerOnnx, EmotiEffLibRecognizerTorch] EmotiEffLibRecognizer(str engine="torch", str model_name="enet_b0_8_best_vgaf", str device="cpu")