8#include <xtensor/containers/xadapt.hpp>
9#include <xtensor/io/xio.hpp>
10#include <xtensor/views/xview.hpp>
23Ort::Value xarray2tensor(xt::xarray<float>& xarray) {
24 auto xtensor = xt::eval(xarray);
26 std::vector<int64_t> shape(xtensor.shape().begin(), xtensor.shape().end());
29 Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
32 Ort::Value onnx_tensor = Ort::Value::CreateTensor<float>(
33 memory_info, xarray.data(), xarray.size(), shape.data(), shape.size());
36 if (!onnx_tensor.IsTensor()) {
37 throw std::runtime_error(
"Error during ONNX tensor creation!");
50xt::xarray<float> tensor2xarray(
const Ort::Value& tensor) {
51 if (!tensor.IsTensor()) {
52 throw std::runtime_error(
"Input ONNX Value is not a tensor!");
56 Ort::TensorTypeAndShapeInfo tensor_info = tensor.GetTensorTypeAndShapeInfo();
57 std::vector<int64_t> shape = tensor_info.GetShape();
60 const float* data_ptr = tensor.GetTensorData<
float>();
61 size_t element_count = tensor_info.GetElementCount();
64 std::vector<size_t> xtensor_shape(shape.begin(), shape.end());
67 xt::xarray<float> result = xt::zeros<float>(xtensor_shape);
68 std::copy(data_ptr, data_ptr + element_count, result.begin());
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!");
86 Ort::SessionOptions session_options;
89 Ort::Session model(env_, fullPipelineModel.c_str(), session_options);
90 models_.push_back(std::move(model));
92 initRecognizer(fullPipelineModel);
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));
107 auto features = tensor2xarray(outputTensors[0]);
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]);
126 throw std::runtime_error(
127 "Model for engagement classification wasn't specified in the config!");
129 throw std::runtime_error(
130 "Not enough features to predict engagement. Sliding window width: " +
132 ", but number of features in a sequence: " + std::to_string(features.shape(0)));
136 std::vector<Ort::Value> inputTensors;
137 inputTensors.push_back(xarray2tensor(featuresSlices));
139 auto scores = tensor2xarray(engClassifierOutput[0]);
145 throw std::runtime_error(
"predictEmotions method requires fillPipeline model or "
146 "featureExtractor and classifier models");
147 auto imgTensor = preprocess(faceImg);
150 std::vector<Ort::Value> inputTensors;
151 inputTensors.push_back(xarray2tensor(imgTensor));
152 auto outputTensors = modelRunWrapper(extractorIdx, inputTensors);
154 xt::xarray<float> scores;
156 auto classifierOutputTensors = modelRunWrapper(
classifierIdx_, outputTensors);
157 scores = tensor2xarray(classifierOutputTensors[0]);
159 scores = tensor2xarray(outputTensors[0]);
167 throw std::runtime_error(
168 "predictEngagement method requires featureExtractor and enagement classifier models");
170 throw std::runtime_error(
171 "Not enough frames to predict engagement. Sliding window width: " +
173 ", but number of frames in video: " + std::to_string(faceImgs.size()));
179void EmotiEffLibRecognizerOnnx::initRecognizer(
const std::string& modelPath) {
182 mean_ = {0.485, 0.456, 0.406};
183 std_ = {0.229, 0.224, 0.225};
184 if (
modelName_.find(
"mbf_") != std::string::npos) {
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) {
190 }
else if (
modelName_.find(
"ddamfnet") != std::string::npos) {
197xt::xarray<float> EmotiEffLibRecognizerOnnx::preprocess(
const cv::Mat& img) {
198 cv::Mat resized_img, float_img, normalized_img;
204 resized_img.convertTo(float_img, CV_32FC3, 1.0 / 255.0);
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];
214 cv::merge(channels, normalized_img);
217 std::vector<float> chwData;
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]);
233 if (!config.modelName.empty()) {
237 Ort::SessionOptions session_options;
239 if (config.fullPipelineEmotionModelPath.empty() && config.featureExtractorPath.empty()) {
240 throw std::runtime_error(
"fullPipelineEmotionModelPath or featureExtractorPath MUST be "
241 "specified in the EmotiEffLibConfig.");
243 if (!config.fullPipelineEmotionModelPath.empty()) {
244 Ort::Session model(env_, config.fullPipelineEmotionModelPath.c_str(), session_options);
245 models_.push_back(std::move(model));
248 if (!config.featureExtractorPath.empty()) {
249 Ort::Session model(env_, config.featureExtractorPath.c_str(), session_options);
250 models_.push_back(std::move(model));
253 if (!config.classifierPath.empty()) {
254 Ort::Session model(env_, config.classifierPath.c_str(), session_options);
255 models_.push_back(std::move(model));
258 if (!config.engagementClassifierPath.empty()) {
259 Ort::Session model(env_, config.engagementClassifierPath.c_str(), session_options);
260 models_.push_back(std::move(model));
265std::vector<Ort::Value>
266EmotiEffLibRecognizerOnnx::modelRunWrapper(
int modelIdx,
const std::vector<Ort::Value>& inputs) {
267 auto& session = models_[modelIdx];
268 checkModelInputs(session);
270 auto input_name = session.GetInputNameAllocated(0, allocator_);
271 std::vector<const char*> inputNames = {input_name.get()};
273 auto outputName = session.GetOutputNameAllocated(0, allocator_);
274 std::vector<const char*> outputNames = {outputName.get()};
277 return session.Run(Ort::RunOptions{
nullptr}, inputNames.data(), inputs.data(), 1,
278 outputNames.data(), 1);
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 imgSize_
Input image size.
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.