8#include <xtensor/containers/xadapt.hpp>
17torch::Tensor xarray2tensor(
const xt::xarray<float>& xtensor) {
18 std::vector<int64_t> shape(xtensor.shape().begin(), xtensor.shape().end());
19 std::vector<float> data(xtensor.begin(), xtensor.end());
21 return torch::from_blob(data.data(), shape, torch::TensorOptions().dtype(torch::kFloat))
33xt::xarray<float> tensor2xarray(
const torch::Tensor& tensor) {
34 torch::Tensor cpu_tensor =
35 tensor.to(torch::kCPU).contiguous();
38 std::vector<size_t> shape(cpu_tensor.sizes().begin(), cpu_tensor.sizes().end());
39 const float* data_ptr = cpu_tensor.data_ptr<
float>();
42 return xt::adapt(data_ptr, cpu_tensor.numel(), xt::no_ownership(), shape);
43 xt::xarray<float> result = xt::zeros<float>(shape);
44 std::copy(data_ptr, data_ptr + tensor.numel(), result.begin());
51 torch::jit::script::Module model = torch::jit::load(fullPipelineModel);
52 model.to(torch::Device(torch::kCPU));
54 models_.push_back(model);
56 initRecognizer(fullPipelineModel);
66 throw std::runtime_error(
"Model for features extraction wasn't specified in the config!");
67 auto imgTensor = preprocess(faceImg);
68 auto input = xarray2tensor(imgTensor);
70 auto features = tensor2xarray(outputTensor);
77 throw std::runtime_error(
78 "Model for emotions classification wasn't specified in the config!");
79 auto input = xarray2tensor(features);
80 auto classifierOutput = models_[
classifierIdx_].forward({input}).toTensor();
81 auto scores = tensor2xarray(classifierOutput);
87 throw std::runtime_error(
88 "Model for engagement classification wasn't specified in the config!");
90 throw std::runtime_error(
91 "Not enough features to predict engagement. Sliding window width: " +
93 ", but number of features in a sequence: " + std::to_string(features.shape(0)));
97 auto input = xarray2tensor(featuresSlices);
99 auto scores = tensor2xarray(engClassifierOutput);
106 throw std::runtime_error(
"predictEmotions method requires fillPipeline model or "
107 "featureExtractor and classifier models");
108 auto imgTensor = preprocess(faceImg);
109 auto input = xarray2tensor(imgTensor);
111 auto outputTensor = models_[extractorIdx].forward({input}).toTensor();
112 xt::xarray<float> scores;
114 auto classifierOutput = models_[
classifierIdx_].forward({outputTensor}).toTensor();
115 scores = tensor2xarray(classifierOutput);
117 scores = tensor2xarray(outputTensor);
125 throw std::runtime_error(
126 "predictEngagement method requires featureExtractor and enagement classifier models");
128 throw std::runtime_error(
129 "Not enough frames to predict engagement. Sliding window width: " +
131 ", but number of frames in video: " + std::to_string(faceImgs.size()));
137void EmotiEffLibRecognizerTorch::initRecognizer(
const std::string& modelPath) {
140 bool isB0 =
modelName_.find(
"_b0_") != std::string::npos;
144xt::xarray<float> EmotiEffLibRecognizerTorch::preprocess(
const cv::Mat& img) {
145 cv::Mat resized, float_img, normalized;
151 resized.convertTo(float_img, CV_32F, 1.0 / 255.0);
154 std::vector<cv::Mat> channels(3);
155 cv::split(float_img, channels);
157 std::vector<float> mean = {0.485f, 0.456f, 0.406f};
158 std::vector<float> std = {0.229f, 0.224f, 0.225f};
160 for (
int i = 0; i < 3; ++i) {
161 channels[i] = (channels[i] - mean[i]) / std[i];
164 cv::merge(channels, normalized);
167 std::vector<float> chwData;
170 for (
int c = 0; c < 3; ++c) {
171 for (
int h = 0; h <
imgSize_; ++h) {
172 for (
int w = 0; w <
imgSize_; ++w) {
173 chwData.push_back(normalized.at<cv::Vec3f>(h, w)[c]);
183 if (!config.modelName.empty()) {
187 if (config.fullPipelineEmotionModelPath.empty() && config.featureExtractorPath.empty()) {
188 throw std::runtime_error(
"fullPipelineEmotionModelPath or featureExtractorPath MUST be "
189 "specified in the EmotiEffLibConfig.");
191 if (!config.fullPipelineEmotionModelPath.empty()) {
192 torch::jit::script::Module model = torch::jit::load(config.fullPipelineEmotionModelPath);
193 model.to(torch::Device(torch::kCPU));
195 models_.push_back(model);
198 if (!config.featureExtractorPath.empty()) {
199 torch::jit::script::Module model = torch::jit::load(config.featureExtractorPath);
200 model.to(torch::Device(torch::kCPU));
202 models_.push_back(model);
205 if (!config.classifierPath.empty()) {
206 torch::jit::script::Module model = torch::jit::load(config.classifierPath);
207 model.to(torch::Device(torch::kCPU));
209 models_.push_back(model);
212 if (!config.engagementClassifierPath.empty()) {
213 torch::jit::script::Module model = torch::jit::load(config.engagementClassifierPath);
214 model.to(torch::Device(torch::kCPU));
216 models_.push_back(model);
Header file for the Torch backend implementation of the EmotiEffLibRecognizer.
EmotiEffLibRes predictEmotions(const cv::Mat &faceImg, bool logits=true) override
Predicts emotions for a single face image.
xt::xarray< float > extractFeatures(const cv::Mat &faceImg) override
Extracts features from a single face image.
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.
EmotiEffLibRecognizerTorch(const std::string &fullPipelineModelPath)
Constructs an EmotiEffLibRecognizerOnnx instance with the specified model path.
EmotiEffLibRes classifyEmotions(const xt::xarray< float > &features, bool logits=true) override
Classifies emotions based on extracted features.
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.