pptinypose.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #include "ultra_infer/vision/keypointdet/pptinypose/pptinypose.h"
  2. #include "ultra_infer/vision/utils/utils.h"
  3. #include "yaml-cpp/yaml.h"
  4. #ifdef ENABLE_PADDLE2ONNX
  5. #include "paddle2onnx/converter.h"
  6. #endif
  7. #include "ultra_infer/vision.h"
  8. namespace ultra_infer {
  9. namespace vision {
  10. namespace keypointdetection {
  11. PPTinyPose::PPTinyPose(const std::string &model_file,
  12. const std::string &params_file,
  13. const std::string &config_file,
  14. const RuntimeOption &custom_option,
  15. const ModelFormat &model_format) {
  16. config_file_ = config_file;
  17. valid_cpu_backends = {Backend::PDINFER, Backend::ORT, Backend::OPENVINO,
  18. Backend::LITE};
  19. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  20. valid_kunlunxin_backends = {Backend::LITE};
  21. valid_rknpu_backends = {Backend::RKNPU2};
  22. runtime_option = custom_option;
  23. runtime_option.model_format = model_format;
  24. runtime_option.model_file = model_file;
  25. runtime_option.params_file = params_file;
  26. initialized = Initialize();
  27. }
  28. bool PPTinyPose::Initialize() {
  29. if (!BuildPreprocessPipelineFromConfig()) {
  30. FDERROR << "Failed to build preprocess pipeline from configuration file."
  31. << std::endl;
  32. return false;
  33. }
  34. if (!InitRuntime()) {
  35. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  36. return false;
  37. }
  38. return true;
  39. }
  40. bool PPTinyPose::BuildPreprocessPipelineFromConfig() {
  41. processors_.clear();
  42. YAML::Node cfg;
  43. try {
  44. cfg = YAML::LoadFile(config_file_);
  45. } catch (YAML::BadFile &e) {
  46. FDERROR << "Failed to load yaml file " << config_file_
  47. << ", maybe you should check this file." << std::endl;
  48. return false;
  49. }
  50. std::string arch = cfg["arch"].as<std::string>();
  51. if (arch != "HRNet" && arch != "HigherHRNet") {
  52. FDERROR << "Require the arch of model is HRNet or HigherHRNet, but arch "
  53. << "defined in "
  54. << "config file is " << arch << "." << std::endl;
  55. return false;
  56. }
  57. processors_.push_back(std::make_shared<BGR2RGB>());
  58. for (const auto &op : cfg["Preprocess"]) {
  59. std::string op_name = op["type"].as<std::string>();
  60. if (op_name == "NormalizeImage") {
  61. if (!disable_normalize_) {
  62. auto mean = op["mean"].as<std::vector<float>>();
  63. auto std = op["std"].as<std::vector<float>>();
  64. bool is_scale = op["is_scale"].as<bool>();
  65. processors_.push_back(std::make_shared<Normalize>(mean, std, is_scale));
  66. }
  67. } else if (op_name == "Permute") {
  68. if (!disable_permute_) {
  69. // permute = cast<float> + HWC2CHW
  70. processors_.push_back(std::make_shared<Cast>("float"));
  71. processors_.push_back(std::make_shared<HWC2CHW>());
  72. }
  73. } else if (op_name == "TopDownEvalAffine") {
  74. auto trainsize = op["trainsize"].as<std::vector<int>>();
  75. int height = trainsize[1];
  76. int width = trainsize[0];
  77. cv::Mat trans_matrix(2, 3, CV_64FC1);
  78. processors_.push_back(
  79. std::make_shared<WarpAffine>(trans_matrix, width, height, 1));
  80. } else {
  81. FDERROR << "Unexcepted preprocess operator: " << op_name << "."
  82. << std::endl;
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. bool PPTinyPose::Preprocess(Mat *mat, std::vector<FDTensor> *outputs) {
  89. for (size_t i = 0; i < processors_.size(); ++i) {
  90. if (processors_[i]->Name().compare("WarpAffine") == 0) {
  91. auto processor = dynamic_cast<WarpAffine *>(processors_[i].get());
  92. float origin_width = static_cast<float>(mat->Width());
  93. float origin_height = static_cast<float>(mat->Height());
  94. std::vector<float> center = {origin_width / 2.0f, origin_height / 2.0f};
  95. std::vector<float> scale = {origin_width, origin_height};
  96. int resize_width = -1;
  97. int resize_height = -1;
  98. std::tie(resize_width, resize_height) = processor->GetWidthAndHeight();
  99. cv::Mat trans_matrix(2, 3, CV_64FC1);
  100. GetAffineTransform(center, scale, 0, {resize_width, resize_height},
  101. &trans_matrix, 0);
  102. if (!(processor->SetTransformMatrix(trans_matrix))) {
  103. FDERROR << "Failed to set transform matrix of "
  104. << processors_[i]->Name() << " processor." << std::endl;
  105. }
  106. }
  107. if (!(*(processors_[i].get()))(mat)) {
  108. FDERROR << "Failed to process image data in " << processors_[i]->Name()
  109. << "." << std::endl;
  110. return false;
  111. }
  112. }
  113. outputs->resize(1);
  114. (*outputs)[0].name = InputInfoOfRuntime(0).name;
  115. mat->ShareWithTensor(&((*outputs)[0]));
  116. // reshape to [1, c, h, w]
  117. (*outputs)[0].ExpandDim(0);
  118. return true;
  119. }
  120. bool PPTinyPose::Postprocess(std::vector<FDTensor> &infer_result,
  121. KeyPointDetectionResult *result,
  122. const std::vector<float> &center,
  123. const std::vector<float> &scale) {
  124. FDASSERT(infer_result[0].shape[0] == 1,
  125. "Only support batch = 1 in UltraInfer now.");
  126. result->Clear();
  127. if (infer_result.size() == 1) {
  128. FDTensor result_copy = infer_result[0];
  129. result_copy.Reshape({result_copy.shape[0], result_copy.shape[1],
  130. result_copy.shape[2] * result_copy.shape[3]});
  131. infer_result.resize(2);
  132. function::ArgMax(result_copy, &infer_result[1], -1);
  133. }
  134. // Calculate output length
  135. int outdata_size =
  136. std::accumulate(infer_result[0].shape.begin(),
  137. infer_result[0].shape.end(), 1, std::multiplies<int>());
  138. int idxdata_size =
  139. std::accumulate(infer_result[1].shape.begin(),
  140. infer_result[1].shape.end(), 1, std::multiplies<int>());
  141. if (outdata_size < 6) {
  142. FDWARNING << "PPTinyPose No object detected." << std::endl;
  143. }
  144. float *out_data = static_cast<float *>(infer_result[0].Data());
  145. void *idx_data = infer_result[1].Data();
  146. int idx_dtype = infer_result[1].dtype;
  147. std::vector<int> out_data_shape(infer_result[0].shape.begin(),
  148. infer_result[0].shape.end());
  149. std::vector<int> idx_data_shape(infer_result[1].shape.begin(),
  150. infer_result[1].shape.end());
  151. std::vector<float> preds(out_data_shape[1] * 3, 0);
  152. std::vector<float> heatmap(out_data, out_data + outdata_size);
  153. std::vector<int64_t> idxout(idxdata_size);
  154. if (idx_dtype == FDDataType::INT32) {
  155. std::copy(static_cast<int32_t *>(idx_data),
  156. static_cast<int32_t *>(idx_data) + idxdata_size, idxout.begin());
  157. } else if (idx_dtype == FDDataType::INT64) {
  158. std::copy(static_cast<int64_t *>(idx_data),
  159. static_cast<int64_t *>(idx_data) + idxdata_size, idxout.begin());
  160. } else {
  161. FDERROR << "Only support process inference result with INT32/INT64 data "
  162. "type, but now it's "
  163. << idx_dtype << "." << std::endl;
  164. }
  165. GetFinalPredictions(heatmap, out_data_shape, idxout, center, scale, &preds,
  166. this->use_dark);
  167. result->Reserve(outdata_size);
  168. result->num_joints = out_data_shape[1];
  169. result->keypoints.clear();
  170. for (int i = 0; i < out_data_shape[1]; i++) {
  171. result->keypoints.push_back({preds[i * 3 + 1], preds[i * 3 + 2]});
  172. result->scores.push_back(preds[i * 3]);
  173. }
  174. return true;
  175. }
  176. bool PPTinyPose::Predict(cv::Mat *im, KeyPointDetectionResult *result) {
  177. std::vector<float> center = {round(im->cols / 2.0f), round(im->rows / 2.0f)};
  178. std::vector<float> scale = {static_cast<float>(im->cols),
  179. static_cast<float>(im->rows)};
  180. Mat mat(*im);
  181. std::vector<FDTensor> processed_data;
  182. if (!Preprocess(&mat, &processed_data)) {
  183. FDERROR << "Failed to preprocess input data while using model:"
  184. << ModelName() << "." << std::endl;
  185. return false;
  186. }
  187. std::vector<FDTensor> infer_result;
  188. if (!Infer(processed_data, &infer_result)) {
  189. FDERROR << "Failed to inference while using model:" << ModelName() << "."
  190. << std::endl;
  191. return false;
  192. }
  193. if (!Postprocess(infer_result, result, center, scale)) {
  194. FDERROR << "Failed to postprocess while using model:" << ModelName() << "."
  195. << std::endl;
  196. return false;
  197. }
  198. return true;
  199. }
  200. bool PPTinyPose::Predict(cv::Mat *im, KeyPointDetectionResult *result,
  201. const DetectionResult &detection_result) {
  202. std::vector<Mat> crop_imgs;
  203. std::vector<std::vector<float>> center_bs;
  204. std::vector<std::vector<float>> scale_bs;
  205. int crop_imgs_num = 0;
  206. int box_num = detection_result.boxes.size();
  207. for (int i = 0; i < box_num; i++) {
  208. auto box = detection_result.boxes[i];
  209. auto label_id = detection_result.label_ids[i];
  210. int channel = im->channels();
  211. cv::Mat cv_crop_img(0, 0, CV_32SC(channel));
  212. Mat crop_img(cv_crop_img);
  213. std::vector<float> rect(box.begin(), box.end());
  214. std::vector<float> center;
  215. std::vector<float> scale;
  216. if (label_id == 0) {
  217. Mat mat(*im);
  218. utils::CropImageByBox(mat, &crop_img, rect, &center, &scale);
  219. center_bs.emplace_back(center);
  220. scale_bs.emplace_back(scale);
  221. crop_imgs.emplace_back(crop_img);
  222. crop_imgs_num += 1;
  223. }
  224. }
  225. for (int i = 0; i < crop_imgs_num; i++) {
  226. std::vector<FDTensor> processed_data;
  227. if (!Preprocess(&crop_imgs[i], &processed_data)) {
  228. FDERROR << "Failed to preprocess input data while using model:"
  229. << ModelName() << "." << std::endl;
  230. return false;
  231. }
  232. std::vector<FDTensor> infer_result;
  233. if (!Infer(processed_data, &infer_result)) {
  234. FDERROR << "Failed to inference while using model:" << ModelName() << "."
  235. << std::endl;
  236. return false;
  237. }
  238. KeyPointDetectionResult one_cropimg_result;
  239. if (!Postprocess(infer_result, &one_cropimg_result, center_bs[i],
  240. scale_bs[i])) {
  241. FDERROR << "Failed to postprocess while using model:" << ModelName()
  242. << "." << std::endl;
  243. return false;
  244. }
  245. if (result->num_joints == -1) {
  246. result->num_joints = one_cropimg_result.num_joints;
  247. }
  248. std::copy(one_cropimg_result.keypoints.begin(),
  249. one_cropimg_result.keypoints.end(),
  250. std::back_inserter(result->keypoints));
  251. std::copy(one_cropimg_result.scores.begin(),
  252. one_cropimg_result.scores.end(),
  253. std::back_inserter(result->scores));
  254. }
  255. return true;
  256. }
  257. } // namespace keypointdetection
  258. } // namespace vision
  259. } // namespace ultra_infer