ocr_rec.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <include/ocr_rec.h>
  15. namespace PaddleOCR {
  16. void CRNNRecognizer::Run(std::vector<cv::Mat> img_list,
  17. std::vector<std::string> &rec_texts,
  18. std::vector<float> &rec_text_scores,
  19. std::vector<double> &times) {
  20. std::chrono::duration<float> preprocess_diff =
  21. std::chrono::steady_clock::now() - std::chrono::steady_clock::now();
  22. std::chrono::duration<float> inference_diff =
  23. std::chrono::steady_clock::now() - std::chrono::steady_clock::now();
  24. std::chrono::duration<float> postprocess_diff =
  25. std::chrono::steady_clock::now() - std::chrono::steady_clock::now();
  26. int img_num = img_list.size();
  27. std::vector<float> width_list;
  28. for (int i = 0; i < img_num; i++) {
  29. width_list.push_back(float(img_list[i].cols) / img_list[i].rows);
  30. }
  31. std::vector<int> indices = Utility::argsort(width_list);
  32. for (int beg_img_no = 0; beg_img_no < img_num;
  33. beg_img_no += this->rec_batch_num_) {
  34. auto preprocess_start = std::chrono::steady_clock::now();
  35. int end_img_no = std::min(img_num, beg_img_no + this->rec_batch_num_);
  36. int batch_num = end_img_no - beg_img_no;
  37. int imgH = this->rec_image_shape_[1];
  38. int imgW = this->rec_image_shape_[2];
  39. float max_wh_ratio = imgW * 1.0 / imgH;
  40. for (int ino = beg_img_no; ino < end_img_no; ino++) {
  41. int h = img_list[indices[ino]].rows;
  42. int w = img_list[indices[ino]].cols;
  43. float wh_ratio = w * 1.0 / h;
  44. max_wh_ratio = std::max(max_wh_ratio, wh_ratio);
  45. }
  46. int batch_width = imgW;
  47. std::vector<cv::Mat> norm_img_batch;
  48. for (int ino = beg_img_no; ino < end_img_no; ino++) {
  49. cv::Mat srcimg;
  50. img_list[indices[ino]].copyTo(srcimg);
  51. cv::Mat resize_img;
  52. this->resize_op_.Run(srcimg, resize_img, max_wh_ratio,
  53. this->use_tensorrt_, this->rec_image_shape_);
  54. this->normalize_op_.Run(&resize_img, this->mean_, this->scale_,
  55. this->is_scale_);
  56. norm_img_batch.push_back(resize_img);
  57. batch_width = std::max(resize_img.cols, batch_width);
  58. }
  59. std::vector<float> input(batch_num * 3 * imgH * batch_width, 0.0f);
  60. this->permute_op_.Run(norm_img_batch, input.data());
  61. auto preprocess_end = std::chrono::steady_clock::now();
  62. preprocess_diff += preprocess_end - preprocess_start;
  63. // Inference.
  64. auto input_names = this->predictor_->GetInputNames();
  65. auto input_t = this->predictor_->GetInputHandle(input_names[0]);
  66. input_t->Reshape({batch_num, 3, imgH, batch_width});
  67. auto inference_start = std::chrono::steady_clock::now();
  68. input_t->CopyFromCpu(input.data());
  69. this->predictor_->Run();
  70. std::vector<float> predict_batch;
  71. auto output_names = this->predictor_->GetOutputNames();
  72. auto output_t = this->predictor_->GetOutputHandle(output_names[0]);
  73. auto predict_shape = output_t->shape();
  74. int out_num = std::accumulate(predict_shape.begin(), predict_shape.end(), 1,
  75. std::multiplies<int>());
  76. predict_batch.resize(out_num);
  77. // predict_batch is the result of Last FC with softmax
  78. output_t->CopyToCpu(predict_batch.data());
  79. auto inference_end = std::chrono::steady_clock::now();
  80. inference_diff += inference_end - inference_start;
  81. // ctc decode
  82. auto postprocess_start = std::chrono::steady_clock::now();
  83. for (int m = 0; m < predict_shape[0]; m++) {
  84. std::string str_res;
  85. int argmax_idx;
  86. int last_index = 0;
  87. float score = 0.f;
  88. int count = 0;
  89. float max_value = 0.0f;
  90. for (int n = 0; n < predict_shape[1]; n++) {
  91. // get idx
  92. argmax_idx = int(Utility::argmax(
  93. &predict_batch[(m * predict_shape[1] + n) * predict_shape[2]],
  94. &predict_batch[(m * predict_shape[1] + n + 1) * predict_shape[2]]));
  95. // get score
  96. max_value = float(*std::max_element(
  97. &predict_batch[(m * predict_shape[1] + n) * predict_shape[2]],
  98. &predict_batch[(m * predict_shape[1] + n + 1) * predict_shape[2]]));
  99. if (argmax_idx > 0 && (!(n > 0 && argmax_idx == last_index))) {
  100. score += max_value;
  101. count += 1;
  102. str_res += label_list_[argmax_idx];
  103. }
  104. last_index = argmax_idx;
  105. }
  106. score /= count;
  107. if (std::isnan(score)) {
  108. continue;
  109. }
  110. rec_texts[indices[beg_img_no + m]] = str_res;
  111. rec_text_scores[indices[beg_img_no + m]] = score;
  112. }
  113. auto postprocess_end = std::chrono::steady_clock::now();
  114. postprocess_diff += postprocess_end - postprocess_start;
  115. }
  116. times.push_back(double(preprocess_diff.count() * 1000));
  117. times.push_back(double(inference_diff.count() * 1000));
  118. times.push_back(double(postprocess_diff.count() * 1000));
  119. }
  120. void CRNNRecognizer::LoadModel(const std::string &model_dir) {
  121. paddle_infer::Config config;
  122. config.SetModel(model_dir + "/inference.pdmodel",
  123. model_dir + "/inference.pdiparams");
  124. std::cout << "In PP-OCRv3, default rec_img_h is 48,"
  125. << "if you use other model, you should set the param rec_img_h=32"
  126. << std::endl;
  127. if (this->use_gpu_) {
  128. config.EnableUseGpu(this->gpu_mem_, this->gpu_id_);
  129. if (this->use_tensorrt_) {
  130. auto precision = paddle_infer::Config::Precision::kFloat32;
  131. if (this->precision_ == "fp16") {
  132. precision = paddle_infer::Config::Precision::kHalf;
  133. }
  134. if (this->precision_ == "int8") {
  135. precision = paddle_infer::Config::Precision::kInt8;
  136. }
  137. if (!Utility::PathExists("./trt_rec_shape.txt")) {
  138. config.CollectShapeRangeInfo("./trt_rec_shape.txt");
  139. } else {
  140. config.EnableTunedTensorRtDynamicShape("./trt_rec_shape.txt", true);
  141. }
  142. }
  143. } else {
  144. config.DisableGpu();
  145. if (this->use_mkldnn_) {
  146. config.EnableMKLDNN();
  147. // cache 10 different shapes for mkldnn to avoid memory leak
  148. config.SetMkldnnCacheCapacity(10);
  149. }
  150. config.SetCpuMathLibraryNumThreads(this->cpu_math_library_num_threads_);
  151. }
  152. // get pass_builder object
  153. auto pass_builder = config.pass_builder();
  154. // delete "matmul_transpose_reshape_fuse_pass"
  155. pass_builder->DeletePass("matmul_transpose_reshape_fuse_pass");
  156. config.SwitchUseFeedFetchOps(false);
  157. // true for multiple input
  158. config.SwitchSpecifyInputNames(true);
  159. config.SwitchIrOptim(true);
  160. config.EnableMemoryOptim();
  161. // config.DisableGlogInfo();
  162. this->predictor_ = paddle_infer::CreatePredictor(config);
  163. }
  164. } // namespace PaddleOCR