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
10namespace {
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());
20
21 return torch::from_blob(data.data(), shape, torch::TensorOptions().dtype(torch::kFloat))
22 .clone();
23}
24
33xt::xarray<float> tensor2xarray(const torch::Tensor& tensor) {
34 torch::Tensor cpu_tensor =
35 tensor.to(torch::kCPU).contiguous(); // Ensure CPU and contiguous memory
36
37 // Get shape and data pointer
38 std::vector<size_t> shape(cpu_tensor.sizes().begin(), cpu_tensor.sizes().end());
39 const float* data_ptr = cpu_tensor.data_ptr<float>();
40
41 // Adapt to xt::xarray
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());
45 return result;
46}
47} // namespace
48
49namespace EmotiEffLib {
50EmotiEffLibRecognizerTorch::EmotiEffLibRecognizerTorch(const std::string& fullPipelineModel) {
51 torch::jit::script::Module model = torch::jit::load(fullPipelineModel);
52 model.to(torch::Device(torch::kCPU));
53 model.eval();
54 models_.push_back(model);
56 initRecognizer(fullPipelineModel);
57}
58
60 configParser(config);
61 initRecognizer(config.featureExtractorPath);
62}
63
64xt::xarray<float> EmotiEffLibRecognizerTorch::extractFeatures(const cv::Mat& faceImg) {
65 if (featureExtractorIdx_ == -1)
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);
69 auto outputTensor = models_[featureExtractorIdx_].forward({input}).toTensor();
70 auto features = tensor2xarray(outputTensor);
71 return features;
72}
73
75 bool logits) {
76 if (classifierIdx_ == -1)
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);
82 return processEmotionScores(scores, logits);
83}
84
87 throw std::runtime_error(
88 "Model for engagement classification wasn't specified in the config!");
89 if (features.shape(0) < engagementSlidingWindowSize_)
90 throw std::runtime_error(
91 "Not enough features to predict engagement. Sliding window width: " +
92 std::to_string(engagementSlidingWindowSize_) +
93 ", but number of features in a sequence: " + std::to_string(features.shape(0)));
94
95 auto featuresSlices = engagementFeaturesPreprocess(features);
96
97 auto input = xarray2tensor(featuresSlices);
98 auto engClassifierOutput = models_[engagementClassifierIdx_].forward({input}).toTensor();
99 auto scores = tensor2xarray(engClassifierOutput);
100
101 return processEngagementScores(scores);
102}
103
105 if (fullPipelineModelIdx_ == -1 && (featureExtractorIdx_ == -1 || classifierIdx_ == -1))
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;
113 if (fullPipelineModelIdx_ == -1 && classifierIdx_ > -1) {
114 auto classifierOutput = models_[classifierIdx_].forward({outputTensor}).toTensor();
115 scores = tensor2xarray(classifierOutput);
116 } else {
117 scores = tensor2xarray(outputTensor);
118 }
119
120 return processEmotionScores(scores, logits);
121}
122
125 throw std::runtime_error(
126 "predictEngagement method requires featureExtractor and enagement classifier models");
127 if (faceImgs.size() < engagementSlidingWindowSize_)
128 throw std::runtime_error(
129 "Not enough frames to predict engagement. Sliding window width: " +
130 std::to_string(engagementSlidingWindowSize_) +
131 ", but number of frames in video: " + std::to_string(faceImgs.size()));
132 auto features = EmotiEffLibRecognizer::extractFeatures(faceImgs);
133
134 return classifyEngagement(features);
135}
136
137void EmotiEffLibRecognizerTorch::initRecognizer(const std::string& modelPath) {
139
140 bool isB0 = modelName_.find("_b0_") != std::string::npos;
141 imgSize_ = isB0 ? 224 : 260;
142}
143
144xt::xarray<float> EmotiEffLibRecognizerTorch::preprocess(const cv::Mat& img) {
145 cv::Mat resized, float_img, normalized;
146
147 // Resize the image to (img_size, img_size)
148 cv::resize(img, resized, cv::Size(imgSize_, imgSize_));
149
150 // Convert to float and scale to [0, 1]
151 resized.convertTo(float_img, CV_32F, 1.0 / 255.0);
152
153 // Normalize using mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225]
154 std::vector<cv::Mat> channels(3);
155 cv::split(float_img, channels);
156
157 std::vector<float> mean = {0.485f, 0.456f, 0.406f};
158 std::vector<float> std = {0.229f, 0.224f, 0.225f};
159
160 for (int i = 0; i < 3; ++i) {
161 channels[i] = (channels[i] - mean[i]) / std[i];
162 }
163
164 cv::merge(channels, normalized);
165
166 // Convert HWC OpenCV Mat to CHW xtensor
167 std::vector<float> chwData;
168 chwData.reserve(3 * imgSize_ * imgSize_);
169
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]);
174 }
175 }
176 }
177
178 // Adapt vector to xt::xarray<float> with NCHW shape
179 return xt::adapt(chwData, {1, 3, imgSize_, imgSize_});
180}
181
182void EmotiEffLibRecognizerTorch::configParser(const EmotiEffLibConfig& config) {
183 if (!config.modelName.empty()) {
184 modelName_ = config.modelName;
185 }
186
187 if (config.fullPipelineEmotionModelPath.empty() && config.featureExtractorPath.empty()) {
188 throw std::runtime_error("fullPipelineEmotionModelPath or featureExtractorPath MUST be "
189 "specified in the EmotiEffLibConfig.");
190 }
191 if (!config.fullPipelineEmotionModelPath.empty()) {
192 torch::jit::script::Module model = torch::jit::load(config.fullPipelineEmotionModelPath);
193 model.to(torch::Device(torch::kCPU));
194 model.eval();
195 models_.push_back(model);
196 fullPipelineModelIdx_ = models_.size() - 1;
197 }
198 if (!config.featureExtractorPath.empty()) {
199 torch::jit::script::Module model = torch::jit::load(config.featureExtractorPath);
200 model.to(torch::Device(torch::kCPU));
201 model.eval();
202 models_.push_back(model);
203 featureExtractorIdx_ = models_.size() - 1;
204 }
205 if (!config.classifierPath.empty()) {
206 torch::jit::script::Module model = torch::jit::load(config.classifierPath);
207 model.to(torch::Device(torch::kCPU));
208 model.eval();
209 models_.push_back(model);
210 classifierIdx_ = models_.size() - 1;
211 }
212 if (!config.engagementClassifierPath.empty()) {
213 torch::jit::script::Module model = torch::jit::load(config.engagementClassifierPath);
214 model.to(torch::Device(torch::kCPU));
215 model.eval();
216 models_.push_back(model);
217 engagementClassifierIdx_ = models_.size() - 1;
218 }
219}
220} // namespace EmotiEffLib
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 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.