"ppocr/git@developer.sourcefind.cn:wangsen/paddle_dbnet.git" did not exist on "253b845309a81645712087a68311e32ebc6ec967"
main.cpp 11.6 KB
Newer Older
MissPenguin's avatar
MissPenguin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "glog/logging.h"
#include "omp.h"
#include "opencv2/core.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include <chrono>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <vector>

#include <cstring>
#include <fstream>
#include <numeric>

#include <glog/logging.h>
#include <include/ocr_det.h>
#include <include/ocr_cls.h>
#include <include/ocr_rec.h>
MissPenguin's avatar
MissPenguin committed
34
#include <include/utility.h>
MissPenguin's avatar
MissPenguin committed
35
36
37
38
39
40
41
42
43
44
#include <sys/stat.h>

#include <gflags/gflags.h>

DEFINE_bool(use_gpu, false, "Infering with GPU or CPU.");
DEFINE_int32(gpu_id, 0, "Device id of GPU to execute.");
DEFINE_int32(gpu_mem, 4000, "GPU id when infering with GPU.");
DEFINE_int32(cpu_math_library_num_threads, 10, "Num of threads with CPU.");
DEFINE_bool(use_mkldnn, false, "Whether use mkldnn with CPU.");
DEFINE_bool(use_tensorrt, false, "Whether use tensorrt.");
MissPenguin's avatar
MissPenguin committed
45
46
47
DEFINE_string(precision, "fp32", "Precision be one of fp32/fp16/int8");
DEFINE_bool(benchmark, true, "Whether use benchmark.");
DEFINE_string(save_log_path, "./log_output/", "Save benchmark log path.");
MissPenguin's avatar
MissPenguin committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// detection related
DEFINE_string(image_dir, "", "Dir of input image.");
DEFINE_string(det_model_dir, "", "Path of det inference model.");
DEFINE_int32(max_side_len, 960, "max_side_len of input image.");
DEFINE_double(det_db_thresh, 0.3, "Threshold of det_db_thresh.");
DEFINE_double(det_db_box_thresh, 0.5, "Threshold of det_db_box_thresh.");
DEFINE_double(det_db_unclip_ratio, 1.6, "Threshold of det_db_unclip_ratio.");
DEFINE_bool(use_polygon_score, false, "Whether use polygon score.");
DEFINE_bool(visualize, true, "Whether show the detection results.");
// classification related
DEFINE_bool(use_angle_cls, false, "Whether use use_angle_cls.");
DEFINE_string(cls_model_dir, "", "Path of cls inference model.");
DEFINE_double(cls_thresh, 0.9, "Threshold of cls_thresh.");
// recognition related
DEFINE_string(rec_model_dir, "", "Path of rec inference model.");
DEFINE_string(char_list_file, "../../ppocr/utils/ppocr_keys_v1.txt", "Path of dictionary.");


using namespace std;
using namespace cv;
using namespace PaddleOCR;


MissPenguin's avatar
MissPenguin committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
void PrintBenchmarkLog(std::string model_name, 
                       int batch_size, 
                       std::string input_shape,
                       std::vector<double> time_info,
                       int img_num){
  LOG(INFO) << "----------------------- Config info -----------------------";
  LOG(INFO) << "runtime_device: " << (FLAGS_use_gpu ? "gpu" : "cpu");
  LOG(INFO) << "ir_optim: " << "True";
  LOG(INFO) << "enable_memory_optim: " << "True";
  LOG(INFO) << "enable_tensorrt: " << FLAGS_use_tensorrt;
  LOG(INFO) << "enable_mkldnn: " << (FLAGS_use_mkldnn ? "True" : "False");
  LOG(INFO) << "cpu_math_library_num_threads: " << FLAGS_cpu_math_library_num_threads;
  LOG(INFO) << "----------------------- Data info -----------------------";
  LOG(INFO) << "batch_size: " << batch_size;
  LOG(INFO) << "input_shape: " << input_shape;
  LOG(INFO) << "data_num: " << img_num;
  LOG(INFO) << "----------------------- Model info -----------------------";
  LOG(INFO) << "model_name: " << model_name;
  LOG(INFO) << "precision: " << FLAGS_precision;
  LOG(INFO) << "----------------------- Perf info ------------------------";
  LOG(INFO) << "Total time spent(ms): "
            << std::accumulate(time_info.begin(), time_info.end(), 0);
  LOG(INFO) << "preprocess_time(ms): " << time_info[0] / img_num
            << ", inference_time(ms): " << time_info[1] / img_num
            << ", postprocess_time(ms): " << time_info[2] / img_num;
}


MissPenguin's avatar
MissPenguin committed
99
100
101
102
103
104
105
106
107
108
109
static bool PathExists(const std::string& path){
#ifdef _WIN32
  struct _stat buffer;
  return (_stat(path.c_str(), &buffer) == 0);
#else
  struct stat buffer;
  return (stat(path.c_str(), &buffer) == 0);
#endif  // !_WIN32
}


MissPenguin's avatar
MissPenguin committed
110
111
int main_det(std::vector<cv::String> cv_all_img_names) {
    std::vector<double> time_info = {0, 0, 0};
MissPenguin's avatar
MissPenguin committed
112
113
114
115
116
    DBDetector det(FLAGS_det_model_dir, FLAGS_use_gpu, FLAGS_gpu_id,
                   FLAGS_gpu_mem, FLAGS_cpu_math_library_num_threads, 
                   FLAGS_use_mkldnn, FLAGS_max_side_len, FLAGS_det_db_thresh,
                   FLAGS_det_db_box_thresh, FLAGS_det_db_unclip_ratio,
                   FLAGS_use_polygon_score, FLAGS_visualize,
MissPenguin's avatar
MissPenguin committed
117
118
                   FLAGS_use_tensorrt, FLAGS_precision);
    
MissPenguin's avatar
MissPenguin committed
119
120
121
122
123
124
125
126
127
    for (int i = 0; i < cv_all_img_names.size(); ++i) {
      LOG(INFO) << "The predict img: " << cv_all_img_names[i];

      cv::Mat srcimg = cv::imread(cv_all_img_names[i], cv::IMREAD_COLOR);
      if (!srcimg.data) {
        std::cerr << "[ERROR] image read failed! image path: " << cv_all_img_names[i] << endl;
        exit(1);
      }
      std::vector<std::vector<std::vector<int>>> boxes;
MissPenguin's avatar
MissPenguin committed
128
      std::vector<double> det_times;
MissPenguin's avatar
MissPenguin committed
129

MissPenguin's avatar
MissPenguin committed
130
131
132
133
134
      det.Run(srcimg, boxes, &det_times);
  
      time_info[0] += det_times[0];
      time_info[1] += det_times[1];
      time_info[2] += det_times[2];
MissPenguin's avatar
MissPenguin committed
135
136
    }
    
MissPenguin's avatar
MissPenguin committed
137
138
139
    if (FLAGS_benchmark) {
        PrintBenchmarkLog("det", 1, "dynamic", time_info, cv_all_img_names.size());
    }
MissPenguin's avatar
MissPenguin committed
140
141
142
143
    return 0;
}


MissPenguin's avatar
MissPenguin committed
144
145
int main_rec(std::vector<cv::String> cv_all_img_names) {
    std::vector<double> time_info = {0, 0, 0};
MissPenguin's avatar
MissPenguin committed
146
147
148
    CRNNRecognizer rec(FLAGS_rec_model_dir, FLAGS_use_gpu, FLAGS_gpu_id,
                       FLAGS_gpu_mem, FLAGS_cpu_math_library_num_threads,
                       FLAGS_use_mkldnn, FLAGS_char_list_file,
MissPenguin's avatar
MissPenguin committed
149
                       FLAGS_use_tensorrt, FLAGS_precision);
MissPenguin's avatar
MissPenguin committed
150
151
152
153
154
155
156
157
158
159

    for (int i = 0; i < cv_all_img_names.size(); ++i) {
      LOG(INFO) << "The predict img: " << cv_all_img_names[i];

      cv::Mat srcimg = cv::imread(cv_all_img_names[i], cv::IMREAD_COLOR);
      if (!srcimg.data) {
        std::cerr << "[ERROR] image read failed! image path: " << cv_all_img_names[i] << endl;
        exit(1);
      }

MissPenguin's avatar
MissPenguin committed
160
161
      std::vector<double> rec_times;
      rec.Run(srcimg, &rec_times);
MissPenguin's avatar
MissPenguin committed
162
        
MissPenguin's avatar
MissPenguin committed
163
164
165
166
167
168
169
      time_info[0] += rec_times[0];
      time_info[1] += rec_times[1];
      time_info[2] += rec_times[2];
    }
    
    if (FLAGS_benchmark) {
        PrintBenchmarkLog("rec", 1, "dynamic", time_info, cv_all_img_names.size());
MissPenguin's avatar
MissPenguin committed
170
171
172
173
174
175
    }
    
    return 0;
}


MissPenguin's avatar
MissPenguin committed
176
int main_system(std::vector<cv::String> cv_all_img_names) {
MissPenguin's avatar
MissPenguin committed
177
178
179
180
181
    DBDetector det(FLAGS_det_model_dir, FLAGS_use_gpu, FLAGS_gpu_id,
                   FLAGS_gpu_mem, FLAGS_cpu_math_library_num_threads, 
                   FLAGS_use_mkldnn, FLAGS_max_side_len, FLAGS_det_db_thresh,
                   FLAGS_det_db_box_thresh, FLAGS_det_db_unclip_ratio,
                   FLAGS_use_polygon_score, FLAGS_visualize,
MissPenguin's avatar
MissPenguin committed
182
                   FLAGS_use_tensorrt, FLAGS_precision);
MissPenguin's avatar
MissPenguin committed
183
184
185
186
187
188

    Classifier *cls = nullptr;
    if (FLAGS_use_angle_cls) {
      cls = new Classifier(FLAGS_cls_model_dir, FLAGS_use_gpu, FLAGS_gpu_id,
                           FLAGS_gpu_mem, FLAGS_cpu_math_library_num_threads,
                           FLAGS_use_mkldnn, FLAGS_cls_thresh,
MissPenguin's avatar
MissPenguin committed
189
                           FLAGS_use_tensorrt, FLAGS_precision);
MissPenguin's avatar
MissPenguin committed
190
191
192
193
194
    }

    CRNNRecognizer rec(FLAGS_rec_model_dir, FLAGS_use_gpu, FLAGS_gpu_id,
                       FLAGS_gpu_mem, FLAGS_cpu_math_library_num_threads,
                       FLAGS_use_mkldnn, FLAGS_char_list_file,
MissPenguin's avatar
MissPenguin committed
195
                       FLAGS_use_tensorrt, FLAGS_precision);
MissPenguin's avatar
MissPenguin committed
196
197
198
199
200
201
202
203
204
205
206
207

    auto start = std::chrono::system_clock::now();

    for (int i = 0; i < cv_all_img_names.size(); ++i) {
      LOG(INFO) << "The predict img: " << cv_all_img_names[i];

      cv::Mat srcimg = cv::imread(FLAGS_image_dir, cv::IMREAD_COLOR);
      if (!srcimg.data) {
        std::cerr << "[ERROR] image read failed! image path: " << cv_all_img_names[i] << endl;
        exit(1);
      }
      std::vector<std::vector<std::vector<int>>> boxes;
MissPenguin's avatar
MissPenguin committed
208
209
210
211
      std::vector<double> det_times;
      std::vector<double> rec_times;
        
      det.Run(srcimg, boxes, &det_times);
MissPenguin's avatar
MissPenguin committed
212
213
214
    
      cv::Mat crop_img;
      for (int j = 0; j < boxes.size(); j++) {
MissPenguin's avatar
MissPenguin committed
215
        crop_img = Utility::GetRotateCropImage(srcimg, boxes[j]);
MissPenguin's avatar
MissPenguin committed
216
217
218
219

        if (cls != nullptr) {
          crop_img = cls->Run(crop_img);
        }
MissPenguin's avatar
MissPenguin committed
220
        rec.Run(crop_img, &rec_times);
MissPenguin's avatar
MissPenguin committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
      }
        
      auto end = std::chrono::system_clock::now();
      auto duration =
          std::chrono::duration_cast<std::chrono::microseconds>(end - start);
      std::cout << "Cost  "
                << double(duration.count()) *
                       std::chrono::microseconds::period::num /
                       std::chrono::microseconds::period::den
                << "s" << std::endl;
    }
      
    return 0;
}


MissPenguin's avatar
MissPenguin committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
void check_params(char* mode) {
    if (strcmp(mode, "det")==0) {
        if (FLAGS_det_model_dir.empty() || FLAGS_image_dir.empty()) {
            std::cout << "Usage[det]: ./ppocr --det_model_dir=/PATH/TO/DET_INFERENCE_MODEL/ "
                      << "--image_dir=/PATH/TO/INPUT/IMAGE/" << std::endl;      
            exit(1);      
        }
    }
    if (strcmp(mode, "rec")==0) {
        if (FLAGS_rec_model_dir.empty() || FLAGS_image_dir.empty()) {
            std::cout << "Usage[rec]: ./ppocr --rec_model_dir=/PATH/TO/REC_INFERENCE_MODEL/ "
                      << "--image_dir=/PATH/TO/INPUT/IMAGE/" << std::endl;      
            exit(1);
        }
    }
    if (strcmp(mode, "system")==0) {
        if ((FLAGS_det_model_dir.empty() || FLAGS_rec_model_dir.empty() || FLAGS_image_dir.empty()) ||
           (FLAGS_use_angle_cls && FLAGS_cls_model_dir.empty())) {
            std::cout << "Usage[system without angle cls]: ./ppocr --det_model_dir=/PATH/TO/DET_INFERENCE_MODEL/ "
                        << "--rec_model_dir=/PATH/TO/REC_INFERENCE_MODEL/ "
                        << "--image_dir=/PATH/TO/INPUT/IMAGE/" << std::endl;
            std::cout << "Usage[system with angle cls]: ./ppocr --det_model_dir=/PATH/TO/DET_INFERENCE_MODEL/ "
                        << "--use_angle_cls=true "
                        << "--cls_model_dir=/PATH/TO/CLS_INFERENCE_MODEL/ "
                        << "--rec_model_dir=/PATH/TO/REC_INFERENCE_MODEL/ "
                        << "--image_dir=/PATH/TO/INPUT/IMAGE/" << std::endl;
            exit(1);      
        }
    }
    if (FLAGS_precision != "fp32" && FLAGS_precision != "fp16" && FLAGS_precision != "int8") {
        cout << "precison should be 'fp32'(default), 'fp16' or 'int8'. " << endl;
        exit(1);
    }
}


MissPenguin's avatar
MissPenguin committed
273
int main(int argc, char **argv) {
MissPenguin's avatar
MissPenguin committed
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    if (argc<=1 || (strcmp(argv[1], "det")!=0 && strcmp(argv[1], "rec")!=0 && strcmp(argv[1], "system")!=0)) {
        std::cout << "Please choose one mode of [det, rec, system] !" << std::endl;
        return -1;
    }
    std::cout << "mode: " << argv[1] << endl;

    // Parsing command-line
    google::ParseCommandLineFlags(&argc, &argv, true);
    check_params(argv[1]);
        
    if (!PathExists(FLAGS_image_dir)) {
        std::cerr << "[ERROR] image path not exist! image_dir: " << FLAGS_image_dir << endl;
        exit(1);      
    }
MissPenguin's avatar
MissPenguin committed
288
    
MissPenguin's avatar
MissPenguin committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    std::vector<cv::String> cv_all_img_names;
    cv::glob(FLAGS_image_dir, cv_all_img_names);
    std::cout << "total images num: " << cv_all_img_names.size() << endl;
    
    if (strcmp(argv[1], "det")==0) {
        return main_det(cv_all_img_names);
    }
    if (strcmp(argv[1], "rec")==0) {
        return main_rec(cv_all_img_names);
    }    
    if (strcmp(argv[1], "system")==0) {
        return main_system(cv_all_img_names);
    } 

MissPenguin's avatar
MissPenguin committed
303
}