EmotiEffCppLib
Cpp implementation of Emotion Efficient Library
Loading...
Searching...
No Matches
facial_analysis.cpp
Go to the documentation of this file.
1
5
7
8#include <xtensor/containers/xadapt.hpp>
9#include <xtensor/io/xio.hpp>
10#include <xtensor/views/xview.hpp>
11
12namespace {
23Ort::Value xarray2tensor(xt::xarray<float>& xarray) {
24 auto xtensor = xt::eval(xarray);
25 // Extract shape
26 std::vector<int64_t> shape(xtensor.shape().begin(), xtensor.shape().end());
27
28 // Create ONNX Runtime memory info (CPU)
29 Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
30
31 // Create ONNX Runtime tensor
32 Ort::Value onnx_tensor = Ort::Value::CreateTensor<float>(
33 memory_info, xarray.data(), xarray.size(), shape.data(), shape.size());
34
35 // Verify tensor is valid
36 if (!onnx_tensor.IsTensor()) {
37 throw std::runtime_error("Error during ONNX tensor creation!");
38 }
39 return onnx_tensor;
40}
41
50xt::xarray<float> tensor2xarray(const Ort::Value& tensor) {
51 if (!tensor.IsTensor()) {
52 throw std::runtime_error("Input ONNX Value is not a tensor!");
53 }
54
55 // Get shape information
56 Ort::TensorTypeAndShapeInfo tensor_info = tensor.GetTensorTypeAndShapeInfo();
57 std::vector<int64_t> shape = tensor_info.GetShape();
58
59 // Get raw data pointer (use GetTensorData instead of GetTensorMutableData)
60 const float* data_ptr = tensor.GetTensorData<float>();
61 size_t element_count = tensor_info.GetElementCount();
62
63 // Convert shape to xtensor format (size_t instead of int64_t)
64 std::vector<size_t> xtensor_shape(shape.begin(), shape.end());
65
66 // Create an xt::xarray and copy the data
67 xt::xarray<float> result = xt::zeros<float>(xtensor_shape);
68 std::copy(data_ptr, data_ptr + element_count, result.begin());
69 return result;
70}
71
77void checkModelInputs(const Ort::Session& session) {
78 if (session.GetInputCount() != 1 || session.GetOutputCount() != 1)
79 throw std::runtime_error("Only models with one input and one output are supported!");
80}
81} // namespace
82
83namespace EmotiEffLib {
84EmotiEffLibRecognizerOnnx::EmotiEffLibRecognizerOnnx(const std::string& fullPipelineModel) {
85 // Define session options
86 Ort::SessionOptions session_options;
87
88 // Load the ONNX model
89 Ort::Session model(env_, fullPipelineModel.c_str(), session_options);
90 models_.push_back(std::move(model));
92 initRecognizer(fullPipelineModel);
93}
94
96 configParser(config);
97 initRecognizer(config.featureExtractorPath);
98}
99
100xt::xarray<float> EmotiEffLibRecognizerOnnx::extractFeatures(const cv::Mat& faceImg) {
101 if (featureExtractorIdx_ == -1)
102 throw std::runtime_error("Model for features extraction wasn't specified in the config!");
103 auto imgTensor = preprocess(faceImg);
104 std::vector<Ort::Value> inputTensors;
105 inputTensors.push_back(xarray2tensor(imgTensor));
106 auto outputTensors = modelRunWrapper(featureExtractorIdx_, inputTensors);
107 auto features = tensor2xarray(outputTensors[0]);
108 return features;
109}
110
112 bool logits) {
113 if (classifierIdx_ == -1)
114 throw std::runtime_error(
115 "Model for emotions classification wasn't specified in the config!");
116 xt::xarray<float> featuresHandler = features;
117 std::vector<Ort::Value> inputTensors;
118 inputTensors.push_back(xarray2tensor(featuresHandler));
119 auto outputTensors = modelRunWrapper(classifierIdx_, inputTensors);
120 auto scores = tensor2xarray(outputTensors[0]);
121 return processEmotionScores(scores, logits);
122}
123
125 if (engagementClassifierIdx_ == -1)
126 throw std::runtime_error(
127 "Model for engagement classification wasn't specified in the config!");
128 if (features.shape(0) < engagementSlidingWindowSize_)
129 throw std::runtime_error(
130 "Not enough features to predict engagement. Sliding window width: " +
131 std::to_string(engagementSlidingWindowSize_) +
132 ", but number of features in a sequence: " + std::to_string(features.shape(0)));
133
134 auto featuresSlices = engagementFeaturesPreprocess(features);
135
136 std::vector<Ort::Value> inputTensors;
137 inputTensors.push_back(xarray2tensor(featuresSlices));
138 auto engClassifierOutput = modelRunWrapper(engagementClassifierIdx_, inputTensors);
139 auto scores = tensor2xarray(engClassifierOutput[0]);
140 return processEngagementScores(scores);
141}
142
143EmotiEffLibRes EmotiEffLibRecognizerOnnx::predictEmotions(const cv::Mat& faceImg, bool logits) {
144 if (fullPipelineModelIdx_ == -1 && (featureExtractorIdx_ == -1 || classifierIdx_ == -1))
145 throw std::runtime_error("predictEmotions method requires fillPipeline model or "
146 "featureExtractor and classifier models");
147 auto imgTensor = preprocess(faceImg);
148
150 std::vector<Ort::Value> inputTensors;
151 inputTensors.push_back(xarray2tensor(imgTensor));
152 auto outputTensors = modelRunWrapper(extractorIdx, inputTensors);
153
154 xt::xarray<float> scores;
155 if (fullPipelineModelIdx_ == -1 && classifierIdx_ > -1) {
156 auto classifierOutputTensors = modelRunWrapper(classifierIdx_, outputTensors);
157 scores = tensor2xarray(classifierOutputTensors[0]);
158 } else {
159 scores = tensor2xarray(outputTensors[0]);
160 }
161
162 return processEmotionScores(scores, logits);
163}
164
167 throw std::runtime_error(
168 "predictEngagement method requires featureExtractor and enagement classifier models");
169 if (faceImgs.size() < engagementSlidingWindowSize_)
170 throw std::runtime_error(
171 "Not enough frames to predict engagement. Sliding window width: " +
172 std::to_string(engagementSlidingWindowSize_) +
173 ", but number of frames in video: " + std::to_string(faceImgs.size()));
174 auto features = EmotiEffLibRecognizer::extractFeatures(faceImgs);
175
176 return classifyEngagement(features);
177}
178
179void EmotiEffLibRecognizerOnnx::initRecognizer(const std::string& modelPath) {
181
182 mean_ = {0.485, 0.456, 0.406};
183 std_ = {0.229, 0.224, 0.225};
184 if (modelName_.find("mbf_") != std::string::npos) {
185 imgSize_ = 112;
186 mean_ = {0.5, 0.5, 0.5};
187 std_ = {0.5, 0.5, 0.5};
188 } else if (modelName_.find("_b2_") != std::string::npos) {
189 imgSize_ = 260;
190 } else if (modelName_.find("ddamfnet") != std::string::npos) {
191 imgSize_ = 112;
192 } else {
193 imgSize_ = 224;
194 }
195}
196
197xt::xarray<float> EmotiEffLibRecognizerOnnx::preprocess(const cv::Mat& img) {
198 cv::Mat resized_img, float_img, normalized_img;
199
200 // Resize the image
201 cv::resize(img, resized_img, cv::Size(imgSize_, imgSize_));
202
203 // Convert to float32 and scale to [0, 1]
204 resized_img.convertTo(float_img, CV_32FC3, 1.0 / 255.0);
205
206 // Normalize each channel
207 std::vector<cv::Mat> channels(3);
208 cv::split(float_img, channels);
209 for (int i = 0; i < 3; i++) {
210 channels[i] = (channels[i] - mean_[i]) / std_[i];
211 }
212
213 // Merge back the channels
214 cv::merge(channels, normalized_img);
215
216 // Convert HWC OpenCV Mat to CHW xtensor
217 std::vector<float> chwData;
218 chwData.reserve(3 * imgSize_ * imgSize_);
219
220 for (int c = 0; c < 3; ++c) {
221 for (int h = 0; h < imgSize_; ++h) {
222 for (int w = 0; w < imgSize_; ++w) {
223 chwData.push_back(normalized_img.at<cv::Vec3f>(h, w)[c]);
224 }
225 }
226 }
227
228 // Adapt vector to xt::xarray<float> with NCHW shape
229 return xt::adapt(chwData, {1, 3, imgSize_, imgSize_});
230}
231
232void EmotiEffLibRecognizerOnnx::configParser(const EmotiEffLibConfig& config) {
233 if (!config.modelName.empty()) {
234 modelName_ = config.modelName;
235 }
236 // Define session options
237 Ort::SessionOptions session_options;
238
239 if (config.fullPipelineEmotionModelPath.empty() && config.featureExtractorPath.empty()) {
240 throw std::runtime_error("fullPipelineEmotionModelPath or featureExtractorPath MUST be "
241 "specified in the EmotiEffLibConfig.");
242 }
243 if (!config.fullPipelineEmotionModelPath.empty()) {
244 Ort::Session model(env_, config.fullPipelineEmotionModelPath.c_str(), session_options);
245 models_.push_back(std::move(model));
246 fullPipelineModelIdx_ = models_.size() - 1;
247 }
248 if (!config.featureExtractorPath.empty()) {
249 Ort::Session model(env_, config.featureExtractorPath.c_str(), session_options);
250 models_.push_back(std::move(model));
251 featureExtractorIdx_ = models_.size() - 1;
252 }
253 if (!config.classifierPath.empty()) {
254 Ort::Session model(env_, config.classifierPath.c_str(), session_options);
255 models_.push_back(std::move(model));
256 classifierIdx_ = models_.size() - 1;
257 }
258 if (!config.engagementClassifierPath.empty()) {
259 Ort::Session model(env_, config.engagementClassifierPath.c_str(), session_options);
260 models_.push_back(std::move(model));
261 engagementClassifierIdx_ = models_.size() - 1;
262 }
263}
264
265std::vector<Ort::Value>
266EmotiEffLibRecognizerOnnx::modelRunWrapper(int modelIdx, const std::vector<Ort::Value>& inputs) {
267 auto& session = models_[modelIdx];
268 checkModelInputs(session);
269
270 auto input_name = session.GetInputNameAllocated(0, allocator_);
271 std::vector<const char*> inputNames = {input_name.get()};
272
273 auto outputName = session.GetOutputNameAllocated(0, allocator_);
274 std::vector<const char*> outputNames = {outputName.get()};
275
276 // Run inference
277 return session.Run(Ort::RunOptions{nullptr}, inputNames.data(), inputs.data(), 1,
278 outputNames.data(), 1);
279}
280} // namespace EmotiEffLib
Header file for the ONNX backend implementation of the EmotiEffLibRecognizer.
EmotiEffLibRes classifyEngagement(const xt::xarray< float > &features) override
Classifies engagement based on extracted features.
EmotiEffLibRes predictEngagement(const std::vector< cv::Mat > &faceImgs) override
Predicts engagement for a sequence of face images.
EmotiEffLibRes classifyEmotions(const xt::xarray< float > &features, bool logits=true) override
Classifies emotions based on extracted features.
xt::xarray< float > extractFeatures(const cv::Mat &faceImg) override
Extracts features from a single face image.
EmotiEffLibRecognizerOnnx(const std::string &fullPipelineModelPath)
Constructs an EmotiEffLibRecognizerOnnx instance with the specified model path.
EmotiEffLibRes predictEmotions(const cv::Mat &faceImg, bool logits=true) override
Predicts emotions for a single face image.
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.
xt::xarray< float > engagementFeaturesPreprocess(const xt::xarray< float > features)
Preprocesses engagement features.
int engagementClassifierIdx_
Index of the engagement classifier model in the array with models.
int featureExtractorIdx_
Index of the model for features extraction in the array with models.
int classifierIdx_
Index of the classifier model in the array with models.
int fullPipelineModelIdx_
Index of the full pipeline model in the array with models.
const int engagementSlidingWindowSize_
Sliding window size for engagement prediction.
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 xt::xarray< float > extractFeatures(const cv::Mat &faceImg)=0
Extracts features from a single face image.
Configuration structure for the EmotiEffLibRecognizer.
std::string featureExtractorPath
Path to the feature extractor model file.
Structure to store the results of EmotiEffLib.