EmotiEffCppLib
Cpp implementation of Emotion Efficient Library
Loading...
Searching...
No Matches
facial_analysis.cpp
Go to the documentation of this file.
1
5
7#ifdef WITH_ONNX
9#endif
10#ifdef WITH_TORCH
12#endif
13
14#include <filesystem>
15
16#include <xtensor/core/xmath.hpp>
17#include <xtensor/misc/xsort.hpp>
18#include <xtensor/views/xview.hpp>
19
20namespace fs = std::filesystem;
21
22namespace EmotiEffLib {
23std::vector<std::string> getAvailableBackends() {
24 return {
25#ifdef WITH_TORCH
26 "torch",
27#endif
28#ifdef WITH_ONNX
29 "onnx",
30#endif
31 };
32}
33
34std::vector<std::string> getSupportedModels(const std::string& backendName) {
35 std::vector<std::string> modelsList = {"enet_b0_8_best_vgaf", "enet_b0_8_best_afew",
36 "enet_b2_8", "enet_b0_8_va_mtl", "enet_b2_7"};
37 if (backendName == "onnx") {
38 modelsList.push_back("mbf_va_mtl");
39 modelsList.push_back("mobilevit_va_mtl");
40 }
41 return modelsList;
42}
43
44std::unique_ptr<EmotiEffLibRecognizer>
45EmotiEffLibRecognizer::createInstance(const std::string& backend,
46 const std::string& fullPipelineModelPath) {
47 checkBackend(backend);
48#ifdef WITH_TORCH
49 if (backend == "torch")
50 return std::make_unique<EmotiEffLibRecognizerTorch>(fullPipelineModelPath);
51#elif defined(WITH_ONNX)
52 return std::make_unique<EmotiEffLibRecognizerOnnx>(fullPipelineModelPath);
53#else
54 throw std::runtime_error("EmotiEffCppLib wasn't compiled with any backend support.");
55#endif
56}
57
58std::unique_ptr<EmotiEffLibRecognizer>
60 checkBackend(config.backend);
61#ifdef WITH_TORCH
62 if (config.backend == "torch")
63 return std::make_unique<EmotiEffLibRecognizerTorch>(config);
64#elif defined(WITH_ONNX)
65 return std::make_unique<EmotiEffLibRecognizerOnnx>(config);
66#else
67 throw std::runtime_error("EmotiEffCppLib wasn't compiled with any backend support.");
68#endif
69}
70
71xt::xarray<float> EmotiEffLibRecognizer::extractFeatures(const std::vector<cv::Mat>& faceImgs) {
72 xt::xarray<float> result;
73 for (size_t i = 0; i < faceImgs.size(); ++i) {
74 auto features = extractFeatures(faceImgs[i]);
75 // We need such workaround for concatenating because of known issue in xtensor:
76 // https://github.com/xtensor-stack/xtensor/issues/2579
77 if (i == 0) {
78 result = xt::zeros<float>({faceImgs.size(), features.shape(1)});
79 }
80 xt::view(result, i, xt::all()) = xt::view(features, 0, xt::all());
81 }
82
83 return result;
84}
85
86EmotiEffLibRes EmotiEffLibRecognizer::predictEmotions(const std::vector<cv::Mat>& faceImgs,
87 bool logits) {
88 EmotiEffLibRes result;
89 result.labels = {};
90 for (size_t i = 0; i < faceImgs.size(); ++i) {
91 auto res = predictEmotions(faceImgs[i], logits);
92 if (i == 0) {
93 result.labels = {};
94 result.scores = xt::zeros<float>({faceImgs.size(), res.scores.shape(1)});
95 }
96 result.labels.insert(result.labels.end(), res.labels.begin(), res.labels.end());
97 // We need such workaround for concatenating because of known issue in xtensor:
98 // https://github.com/xtensor-stack/xtensor/issues/2579
99 xt::view(result.scores, i, xt::all()) = xt::view(res.scores, 0, xt::all());
100 }
101 return result;
102}
103
104void EmotiEffLibRecognizer::initRecognizer(const std::string& modelPath) {
105 // Do not change modelName if it was explicitly specified in the config
106 if (modelName_.empty()) {
107 modelName_ = fs::path(modelPath).filename().string();
108 }
109 isMtl_ = modelName_.find("_mtl") != std::string::npos;
110 bool is7 = modelName_.find("_7") != std::string::npos;
111 if (is7) {
112 idxToEmotionClass_.resize(7);
113 idxToEmotionClass_[0] = "Anger";
114 idxToEmotionClass_[1] = "Disgust";
115 idxToEmotionClass_[2] = "Fear";
116 idxToEmotionClass_[3] = "Happiness";
117 idxToEmotionClass_[4] = "Neutral";
118 idxToEmotionClass_[5] = "Sadness";
119 idxToEmotionClass_[6] = "Surprise";
120 } else {
121 idxToEmotionClass_.resize(8);
122 idxToEmotionClass_[0] = "Anger";
123 idxToEmotionClass_[1] = "Contempt";
124 idxToEmotionClass_[2] = "Disgust";
125 idxToEmotionClass_[3] = "Fear";
126 idxToEmotionClass_[4] = "Happiness";
127 idxToEmotionClass_[5] = "Neutral";
128 idxToEmotionClass_[6] = "Sadness";
129 idxToEmotionClass_[7] = "Surprise";
130 }
131}
132
134 bool logits) {
135 xt::xarray<float> x;
136 xt::xarray<float> scores = score;
137 // Select relevant part of the scores based on is_mtl
138 if (isMtl_) {
139 x = xt::view(scores, xt::all(),
140 xt::range(xt::placeholders::_, -2)); // Equivalent to scores[:, :-2]
141 } else {
142 x = scores;
143 }
144
145 // Compute predictions
146 auto preds = xt::argmax(x, 1);
147
148 // Apply softmax if logits is false
149 if (!logits) {
150 xt::xarray<float> max_x = xt::amax(x, {1}, xt::evaluation_strategy::immediate);
151 xt::xarray<float> e_x = xt::exp(x - max_x);
152 e_x /= xt::sum(e_x, {1}, xt::evaluation_strategy::immediate);
153
154 if (isMtl_) {
155 xt::view(scores, xt::all(), xt::range(xt::placeholders::_, -2)) =
156 e_x; // Modify in-place
157 } else {
158 scores = e_x; // Replace scores with softmaxed values
159 }
160 }
161
162 // Convert predictions to emotion class names
163 EmotiEffLibRes res;
164 for (auto pred : preds) {
165 res.labels.push_back(idxToEmotionClass_[pred]);
166 }
167 res.scores = scores;
168 return res;
169}
170
172 // Compute predictions
173 auto preds = xt::argmax(score, 1);
174
175 // Convert predictions to engagement class names
176 EmotiEffLibRes res;
177 for (auto pred : preds) {
178 res.labels.push_back(idxToEngagementClass_[pred]);
179 }
180 res.scores = score;
181 return res;
182}
183
184xt::xarray<float>
186 int maxIters = features.shape(0) - engagementSlidingWindowSize_;
187 xt::xarray<float> features_slices;
188 for (int i = 0; i < maxIters; ++i) {
189 if (i == 0) {
190 features_slices = xt::zeros<float>({static_cast<size_t>(maxIters),
191 static_cast<size_t>(engagementSlidingWindowSize_),
192 features.shape(1) * 2});
193 }
194 auto x = xt::view(features, xt::range(i, i + engagementSlidingWindowSize_), xt::all());
195 auto mean_x = xt::repeat(xt::expand_dims(xt::stddev(x, {0}), 0), x.shape(0), 0);
196 xt::view(features_slices, i, xt::all()) = xt::concatenate(xt::xtuple(mean_x, x), 1);
197 }
198 return features_slices;
199}
200
201void EmotiEffLibRecognizer::checkBackend(const std::string& backend) {
202 auto backends = getAvailableBackends();
203 auto it = std::find(backends.begin(), backends.end(), backend);
204 if (it == backends.end()) {
205 throw std::runtime_error(
206 "This backend (" + backend +
207 ") is not supported. Please check your EmotiEffLib build or configuration.");
208 }
209}
210
211} // namespace EmotiEffLib
Header file for the ONNX backend implementation of the EmotiEffLibRecognizer.
Header file for the Torch backend implementation of the EmotiEffLibRecognizer.
virtual void initRecognizer(const std::string &modelPath)
Initializes the internal state of recognizer based on a modelPath.
EmotiEffLibRes processEngagementScores(const xt::xarray< float > &scores)
Common method to processes engagement scores and generate classification results.
bool isMtl_
Whether the model is multi-task learning (MTL).
xt::xarray< float > engagementFeaturesPreprocess(const xt::xarray< float > features)
Preprocesses engagement features.
static std::unique_ptr< EmotiEffLibRecognizer > createInstance(const std::string &backend, const std::string &fullPipelineModelPath)
Creates an instance of the EmotiEffLibRecognizer with the specified backend and model path.
const int engagementSlidingWindowSize_
Sliding window size for engagement prediction.
std::vector< std::string > idxToEngagementClass_
Engagement class names.
std::vector< std::string > idxToEmotionClass_
Emotion class names.
EmotiEffLibRes processEmotionScores(const xt::xarray< float > &scores, bool logits)
Common method to processes emotion scores and generate classification results.
std::string modelName_
Name of the model.
virtual EmotiEffLibRes predictEmotions(const cv::Mat &faceImg, bool logits=true)=0
Predicts emotions for a single face image.
virtual xt::xarray< float > extractFeatures(const cv::Mat &faceImg)=0
Extracts features from a single face image.
Header file for the EmotiEffLib library, providing emotion and engagement recognition functionality.
std::vector< std::string > getAvailableBackends()
Retrieves the list of available inference backends.
std::vector< std::string > getSupportedModels(const std::string &backendName)
Retrieves the list of supported emotion or engagement recognition models.
Configuration structure for the EmotiEffLibRecognizer.
std::string backend
The inference backend to use.
Structure to store the results of EmotiEffLib.
xt::xarray< float > scores
The confidence scores for each input frame.
std::vector< std::string > labels
The predicted emotion/engagement labels.