"sgl-kernel/python/vscode:/vscode.git/clone" did not exist on "0edda32001938b578976409216bc6f9f36f719df"
ocr_engine.cpp 32.2 KB
Newer Older
liuhy's avatar
liuhy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "ocr_engine.hpp"
#include <iostream>
#include <chrono>
#include <cmath>

using namespace migraphxSamples;

template <typename T>
T clip(const T &n, const T &lower, const T &upper){
    return std::max(lower, std::min(n, upper));
}

template<class ForwardIterator>
liuhy's avatar
liuhy committed
14
inline size_t argmax(ForwardIterator first, ForwardIterator last){
liuhy's avatar
liuhy committed
15
16
17
    return std::distance(first, std::max_element(first, last));
}

liuhy's avatar
liuhy committed
18
static float sigmoid(float x){
liuhy's avatar
liuhy committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    return (1 / (1 + exp(-x)));
}

template <class T> inline T clamp(T x, T min, T max) {
    if (x > max)
      return max;
    if (x < min)
      return min;
    return x;
}

inline float clampf(float x, float min, float max) {
    if (x > max)
        return max;
    if (x < min)
        return min;
    return x;
}

inline int _max(int a, int b) { return a >= b ? a : b; }

inline int _min(int a, int b) { return a >= b ? b : a; }


bool XsortFp32(std::vector<float> a, std::vector<float> b) {
        if (a[0] != b[0])
            return a[0] < b[0];
        return false;
    }
    
    bool XsortInt(std::vector<int> a, std::vector<int> b) {
        if (a[0] != b[0])
            return a[0] < b[0];
        return false;
    }
54
namespace ppocr{
liuhy's avatar
liuhy committed
55
56
57
58
    OcrDet::OcrDet(const std::string det_model_path,
            std::string precision_mode,
            bool offload_copy,
            float segm_thres,
59
            float box_thresh ){
liuhy's avatar
liuhy committed
60
61
62
63
64
65
66
67
68
69
70
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
       if(!Exists(det_model_path))
        {
            LOG_ERROR(stdout, "onnx file not exists!\n");
            exit(0);
        }
        
        this->max_candidates = 1000;
        this->det_batch_size = 1;
        this->segm_thres = segm_thres;
        this->box_thres  = box_thresh;
        this->precision_mode = precision_mode;

        
        
        migraphx::onnx_options onnx_options;
        onnx_options.map_input_dims["x"] = {8, 3, 640, 640};

        net = migraphx::parse_onnx(det_model_path,onnx_options);
        LOG_INFO(stdout, "Succeed to load model: %s\n", GetFileName(det_model_path).c_str());

        if(this->precision_mode.compare("fp16")==0)
        {
            LOG_INFO(stdout, "Set precison mode: %s\n",this->precision_mode.c_str());
            migraphx::quantize_fp16(net);
        }


        std::unordered_map<std::string, migraphx::shape> inputs  = net.get_inputs();
        std::unordered_map<std::string, migraphx::shape> outputs = net.get_outputs();
        this->input_name   = inputs.begin()->first;
        this->input_shape  = inputs.begin()->second;
        this->output_name  = outputs.begin()->first;
        this->output_shape = outputs.begin()->second;

        int N            = this->input_shape.lens()[0];
        int C            = this->input_shape.lens()[1];
        int H            = this->input_shape.lens()[2];
        int W            = this->input_shape.lens()[3];
        this->data_size  = N*C*H*W;
        data =(float*)malloc(C*H*W*sizeof(float));

        net_input_width = W;
        net_input_height = H;
        net_input_channel = C;

        n_channel     =  this->output_shape.lens()[1];
        output_width  =  this->output_shape.lens()[3];
        output_height =  this->output_shape.lens()[2];
        feature_size  =  output_width*output_height;

        
        this->offload_copy = offload_copy;
        migraphx::compile_options options;
        options.device_id = 0; // default device cuda:0
        options.offload_copy = offload_copy;
        migraphx::target gpuTarget = migraphx::gpu::target{};
        net.compile(gpuTarget, options);
117
118
119

        float *warm_data = (float*)malloc(this->input_shape.bytes());
        memset(warm_data, 1.0, this->input_shape.bytes());
liuhy's avatar
liuhy committed
120
121
122
123
124
125
126
127
128
        if( this->offload_copy ==false )
        {
            hipMalloc(&input_buffer_device, this->input_shape.bytes());
            hipMalloc(&output_buffer_device, this->output_shape.bytes());
            output_buffer_host   =  (void*)malloc(this->output_shape.bytes());

            dev_argument[input_name]  = migraphx::argument{input_shape, input_buffer_device};
            dev_argument[output_name] = migraphx::argument{output_shape, output_buffer_device};

129
130
131
132
133
134
135
136
137
138
139
140
141
             hipMemcpy(input_buffer_device,
                  (void*)warm_data,
                  this->input_shape.bytes(),
                  hipMemcpyHostToDevice);
            //warm up
            std::vector<migraphx::argument> results = net.eval(dev_argument);
        }else{
            std::unordered_map<std::string, migraphx::argument> inputData;
            inputData[input_name] = migraphx::argument{input_shape, (float *)warm_data};
            //warm up
            std::vector<migraphx::argument> results = net.eval(inputData);
        }
        free(warm_data);
liuhy's avatar
liuhy committed
142
143
    }

144
    OcrDet::~OcrDet(){
liuhy's avatar
liuhy committed
145
146
147
148
149
150
151
        if(data)
        {
            free(data);
            data = nullptr;
        }
        if( offload_copy == false )
        {
152
            //内存释放
liuhy's avatar
liuhy committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
            if(input_buffer_device)
            {
                hipFree(input_buffer_device);
            }
            if(output_buffer_device)
            {
                hipFree(output_buffer_device);
            }

            if(output_buffer_host)
            {
                free(output_buffer_host);
            }
        }
    }

169
    cv::Size OcrDet::preproc(cv::Mat img,float* data){
liuhy's avatar
liuhy committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        float scale = 1.0/255.0;
        std::vector<float> s_mean={0.485, 0.456, 0.406};
        std::vector<float> s_stdv={0.229, 0.224, 0.225};
        if(img.empty())
        {
            std::cout<<"Source image is empty!\n";
            return cv::Size(1.0,1.0);
        }
        cv::Mat res_img;
        cv::Size scale_r;
        scale_r.width = float(net_input_width)/float(img.cols);
        scale_r.height = float(net_input_height)/float(img.rows);

        cv::resize(img,res_img,cv::Size(net_input_width,net_input_height)); 
        int iw = res_img.cols;
        int ih = res_img.rows;
        memset(data,0.0,3*iw*ih*sizeof(float));
        for(int i=0;i<net_input_height;i++)
        {
            for(int j=0;j<net_input_width;j++)
            { 
                data[i*net_input_width+j+2*net_input_height*net_input_width] = (float(res_img.at<cv::Vec3b>(i, j)[2])*scale-s_mean[2])/s_stdv[2];
                data[i*net_input_width+j+net_input_height*net_input_width] =   (float(res_img.at<cv::Vec3b>(i, j)[1])*scale-s_mean[1])/s_stdv[1];
                data[i*net_input_width+j] =                                    (float(res_img.at<cv::Vec3b>(i, j)[0])*scale-s_mean[0])/s_stdv[0];   
            }
        }
        return  scale_r ;
    }
    
199
    std::vector<std::vector<float>> OcrDet::get_mini_boxes(cv::RotatedRect box,float &ssid) {
liuhy's avatar
liuhy committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
        ssid = max(box.size.width, box.size.height);
        cv::Mat points;
        cv::boxPoints(box, points);

        auto array = Mat2Vector(points);
        std::sort(array.begin(), array.end(), XsortFp32);

        std::vector<float> idx1 = array[0], idx2 = array[1], idx3 = array[2],
                            idx4 = array[3];
        if (array[3][1] <= array[2][1]) {
            idx2 = array[3];
            idx3 = array[2];
        } else {
            idx2 = array[2];
            idx3 = array[3];
        }
        if (array[1][1] <= array[0][1]) {
            idx1 = array[1];
            idx4 = array[0];
        } else {
            idx1 = array[0];
            idx4 = array[1];
        }

        array[0] = idx1;
        array[1] = idx2;
        array[2] = idx3;
        array[3] = idx4;

        return array;
    }

    std::vector<std::vector<std::vector<int>>>OcrDet::boxes_from_bitmap(
    const cv::Mat pred, const cv::Mat bitmap, const float &box_thresh,
    const float &det_db_unclip_ratio, const bool &use_polygon_score) {
        const int min_size = 3;
        const int max_candidates = 1000;

        int width = bitmap.cols;
        int height = bitmap.rows;

        std::vector<std::vector<cv::Point>> contours;
        std::vector<cv::Vec4i> hierarchy;

        cv::findContours(bitmap, contours, hierarchy, cv::RETR_LIST,
                        cv::CHAIN_APPROX_SIMPLE);

        int num_contours =
            contours.size() >= max_candidates ? max_candidates : contours.size();

        std::vector<std::vector<std::vector<int>>> boxes;

        for (int _i = 0; _i < num_contours; _i++) {
            if (contours[_i].size() <= 2) {
            continue;
            }
            float ssid;
            cv::RotatedRect box = cv::minAreaRect(contours[_i]);
            auto array = get_mini_boxes(box, ssid);

            auto box_for_unclip = array;

            if (ssid < min_size) {
            continue;
            }

            float score;
            if (use_polygon_score)
268
269
                //多边形区域的平均得分作为box的分数
                score = polygon_score_acc(contours[_i], pred);
liuhy's avatar
liuhy committed
270
            else
271
             score = box_score_fast(array, pred);
liuhy's avatar
liuhy committed
272
273

            if (score < box_thresh)
274
                continue;
liuhy's avatar
liuhy committed
275

276
            //简化边界得到准确的边界
liuhy's avatar
liuhy committed
277
278
            cv::RotatedRect points = unClip(box_for_unclip, det_db_unclip_ratio);
            if (points.size.height < 1.001 && points.size.width < 1.001) {
279
                continue;
liuhy's avatar
liuhy committed
280
281
282
283
284
285
286
287
288
289
290
291
292
            }

            cv::RotatedRect clipbox = points;
            auto cliparray = get_mini_boxes(clipbox, ssid);

            if (ssid < min_size + 2)
            continue;

            int dest_width = pred.cols;
            int dest_height = pred.rows;
            std::vector<std::vector<int>> intcliparray;

            for (int num_pt = 0; num_pt < 4; num_pt++) {
293
294
295
296
297
298
299
                std::vector<int> a{int(clampf(roundf(cliparray[num_pt][0] / float(width) *
                                                    float(dest_width)),
                                                0, float(dest_width))),
                                    int(clampf(roundf(cliparray[num_pt][1] /
                                                    float(height) * float(dest_height)),
                                                0, float(dest_height)))};
                intcliparray.push_back(a);
liuhy's avatar
liuhy committed
300
301
302
            }
            boxes.push_back(intcliparray);

303
        }
liuhy's avatar
liuhy committed
304
305
306
        return boxes;
    }

307
    std::vector<std::vector<float>> OcrDet::Mat2Vector(cv::Mat mat){
liuhy's avatar
liuhy committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
        std::vector<std::vector<float>> img_vec;
        std::vector<float> tmp;

        for (int i = 0; i < mat.rows; ++i) {
            tmp.clear();
            for (int j = 0; j < mat.cols; ++j) {
            tmp.push_back(mat.at<float>(i, j));
            }
            img_vec.push_back(tmp);
        }
        return img_vec;
    }
    
    float  OcrDet::polygon_score_acc(std::vector<cv::Point> contour,
322
                                     cv::Mat pred){
liuhy's avatar
liuhy committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        int width = pred.cols;
        int height = pred.rows;
        std::vector<float> box_x;
        std::vector<float> box_y;
        for (int i = 0; i < contour.size(); ++i) {
            box_x.push_back(contour[i].x);
            box_y.push_back(contour[i].y);
        }

        int xmin =
            clamp(int(std::floor(*(std::min_element(box_x.begin(), box_x.end())))), 0,
                    width - 1);
        int xmax =
            clamp(int(std::ceil(*(std::max_element(box_x.begin(), box_x.end())))), 0,
                    width - 1);
        int ymin =
            clamp(int(std::floor(*(std::min_element(box_y.begin(), box_y.end())))), 0,
                    height - 1);
        int ymax =
            clamp(int(std::ceil(*(std::max_element(box_y.begin(), box_y.end())))), 0,
                    height - 1);

        cv::Mat mask;
        mask = cv::Mat::zeros(ymax - ymin + 1, xmax - xmin + 1, CV_8UC1);


        cv::Point* rook_point = new cv::Point[contour.size()];
        
        for (int i = 0; i < contour.size(); ++i) {
            rook_point[i] = cv::Point(int(box_x[i]) - xmin, int(box_y[i]) - ymin);
        }
        const cv::Point *ppt[1] = {rook_point};
        int npt[] = {int(contour.size())};


        cv::fillPoly(mask, ppt, npt, 1, cv::Scalar(1));

        cv::Mat croppedImg;
        pred(cv::Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)).copyTo(croppedImg);
        float score = cv::mean(croppedImg, mask)[0];

        delete []rook_point;
        return score;
    }
    
    float OcrDet::box_score_fast(std::vector<std::vector<float>> box_array,
369
                                  cv::Mat pred) {
liuhy's avatar
liuhy committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
        auto array = box_array;
        int width = pred.cols;
        int height = pred.rows;

        float box_x[4] = {array[0][0], array[1][0], array[2][0], array[3][0]};
        float box_y[4] = {array[0][1], array[1][1], array[2][1], array[3][1]};

        int xmin = clamp(int(std::floor(*(std::min_element(box_x, box_x + 4)))), 0,
                        width - 1);
        int xmax = clamp(int(std::ceil(*(std::max_element(box_x, box_x + 4)))), 0,
                        width - 1);
        int ymin = clamp(int(std::floor(*(std::min_element(box_y, box_y + 4)))), 0,
                        height - 1);
        int ymax = clamp(int(std::ceil(*(std::max_element(box_y, box_y + 4)))), 0,
                        height - 1);

        cv::Mat mask;
        mask = cv::Mat::zeros(ymax - ymin + 1, xmax - xmin + 1, CV_8UC1);

        cv::Point root_point[4];
        root_point[0] = cv::Point(int(array[0][0]) - xmin, int(array[0][1]) - ymin);
        root_point[1] = cv::Point(int(array[1][0]) - xmin, int(array[1][1]) - ymin);
        root_point[2] = cv::Point(int(array[2][0]) - xmin, int(array[2][1]) - ymin);
        root_point[3] = cv::Point(int(array[3][0]) - xmin, int(array[3][1]) - ymin);
        const cv::Point *ppt[1] = {root_point};
        int npt[] = {4};
        cv::fillPoly(mask, ppt, npt, 1, cv::Scalar(1));

        cv::Mat croppedImg;
        pred(cv::Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
            .copyTo(croppedImg);

        auto score = cv::mean(croppedImg, mask)[0];
        return score;
   }
    cv::RotatedRect OcrDet::unClip(std::vector<std::vector<float>> box,
406
                                      const float &unclip_ratio){
liuhy's avatar
liuhy committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        float distance = 1.0;
        get_contour_area(box, unclip_ratio, distance);
        ClipperLib::ClipperOffset offset;
        ClipperLib::Path p;
        p << ClipperLib::IntPoint(int(box[0][0]), int(box[0][1]))
            << ClipperLib::IntPoint(int(box[1][0]), int(box[1][1]))
            << ClipperLib::IntPoint(int(box[2][0]), int(box[2][1]))
            << ClipperLib::IntPoint(int(box[3][0]), int(box[3][1]));
        offset.AddPath(p, ClipperLib::jtRound, ClipperLib::etClosedPolygon);

        ClipperLib::Paths soln;
        offset.Execute(soln, distance);
        std::vector<cv::Point2f> points;

        for (int j = 0; j < soln.size(); j++) {
            for (int i = 0; i < soln[soln.size() - 1].size(); i++) {
            points.emplace_back(soln[j][i].X, soln[j][i].Y);
            }
        }
        cv::RotatedRect res;
        if (points.size() <= 0) {
            res = cv::RotatedRect(cv::Point2f(0, 0), cv::Size2f(1, 1), 0);
        } else {
            res = cv::minAreaRect(points);
        }
        return res;
    }
    
    void OcrDet::get_contour_area(const std::vector<std::vector<float>> &box,
436
                                   float unclip_ratio, float &distance) {
liuhy's avatar
liuhy committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
        int pts_num = 4;
        float area = 0.0f;
        float dist = 0.0f;
        for (int i = 0; i < pts_num; i++) {
            area += box[i][0] * box[(i + 1) % pts_num][1] -
                    box[i][1] * box[(i + 1) % pts_num][0];
            dist += sqrtf((box[i][0] - box[(i + 1) % pts_num][0]) *
                            (box[i][0] - box[(i + 1) % pts_num][0]) +
                        (box[i][1] - box[(i + 1) % pts_num][1]) *
                            (box[i][1] - box[(i + 1) % pts_num][1]));
        }
        area = fabs(float(area / 2.0));
        distance = area * unclip_ratio / dist;
    }
    
    std::vector<std::vector<std::vector<int>>>
    OcrDet::filter_det_res(std::vector<std::vector<std::vector<int>>> boxes,
454
                                float ratio_h, float ratio_w, cv::Mat srcimg){
liuhy's avatar
liuhy committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        int oriimg_h = srcimg.rows;
        int oriimg_w = srcimg.cols;

        std::vector<std::vector<std::vector<int>>> root_points;
        for (int n = 0; n < boxes.size(); n++) {
            boxes[n] = order_points_clockwise(boxes[n]);
            for (int m = 0; m < boxes[0].size(); m++) {
            boxes[n][m][0] /= ratio_w;
            boxes[n][m][1] /= ratio_h;

            boxes[n][m][0] = int(_min(_max(boxes[n][m][0], 0), oriimg_w - 1));
            boxes[n][m][1] = int(_min(_max(boxes[n][m][1], 0), oriimg_h - 1));
            }
        }

        for (int n = 0; n < boxes.size(); n++) {
            int rect_width, rect_height;
            rect_width = int(sqrt(pow(boxes[n][0][0] - boxes[n][1][0], 2) +
                                pow(boxes[n][0][1] - boxes[n][1][1], 2)));
            rect_height = int(sqrt(pow(boxes[n][0][0] - boxes[n][3][0], 2) +
                                pow(boxes[n][0][1] - boxes[n][3][1], 2)));
            if (rect_width <= 4 || rect_height <= 4)
            continue;
            root_points.push_back(boxes[n]);
        }
        return root_points;
    }
    
483
    std::vector<std::vector<int>> OcrDet::order_points_clockwise(std::vector<std::vector<int>> pts){
liuhy's avatar
liuhy committed
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
        std::vector<std::vector<int>> box = pts;
        std::sort(box.begin(), box.end(), XsortInt);
        std::vector<std::vector<int>> leftmost = {box[0], box[1]};
        std::vector<std::vector<int>> rightmost = {box[2], box[3]};

        if (leftmost[0][1] > leftmost[1][1])
            std::swap(leftmost[0], leftmost[1]);

        if (rightmost[0][1] > rightmost[1][1])
            std::swap(rightmost[0], rightmost[1]);

        std::vector<std::vector<int>> rect = {leftmost[0], rightmost[0], rightmost[1],
                                                leftmost[1]};
        return rect;
    }

    bool OcrDet::text_recognition(const cv::Mat &srcimg,
501
        const std::vector<std::vector<std::vector<int>>> &boxes){
liuhy's avatar
liuhy committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
        if(boxes.size() == 0)
        {
            std::cout<<"Not found text roi !\n";
            return false;
        }
        std::vector<cv::Point> boundingPoint;
        for (int n = 0; n < boxes.size(); n++) {
            
            cv::Rect rect;
            cv::Mat text_mat;
            rect.x = boxes[n][0][0];
            rect.y = boxes[n][0][1];
            rect.width = boxes[n][2][0] - boxes[n][0][0];
            rect.height = boxes[n][2][1] - boxes[n][0][1];
            text_mat = srcimg(rect).clone();
             
        }   
        return true;
    }
521
    int OcrDet::postprocess(float* feature, std::vector<std::vector<std::vector<int>>> &boxes){
liuhy's avatar
liuhy committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
        int batch_s = 1;
        float conf_thres = 0.6;
        cv::Mat thres_mat = cv::Mat(cv::Size(output_height,output_width), CV_8UC1);
        int feat_size = 20;
        for(int n =0; n< batch_s; n++)
        {
            for (int c =0 ;c<n_channel;c++)
            {
                for(int h = 0;h<output_height;h++)
                {
                    for(int w =0;w<output_width;w++)
                    {
                        thres_mat.at<uchar>(h,w) = feature[n*feature_size*n_channel+c*feature_size+h*output_width+w] > conf_thres ? 1: 0;
                    }
                }
            }
        }
        boxes.clear();
        cv::Mat dilation_map;
        cv::Mat dila_ele = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2, 2));
        cv::dilate(thres_mat, dilation_map, dila_ele);
        boxes = boxes_from_bitmap(thres_mat, dilation_map, 0.6,1.5, false);
        return 0;        
    }

547
    bool OcrDet::forward(cv::Mat& img,std::vector<std::vector<std::vector<int>>>& text_roi_boxes){
liuhy's avatar
liuhy committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
        std::vector<std::vector<std::vector<int>>> boxes;
        cv::Size ratio = preproc(img,data);
        
        if( this->offload_copy ==false )
        {
            hipMemcpy(input_buffer_device,
                  (void*)data,
                  this->input_shape.bytes(),
                  hipMemcpyHostToDevice);

            std::vector<migraphx::argument> results = net.eval(dev_argument);
          
            hipMemcpy(output_buffer_host,
            (void*)output_buffer_device,
            output_shape.bytes(),
            hipMemcpyDeviceToHost);
            postprocess((float *)output_buffer_host,boxes);
            std::cout<<"copy mode ..."<<std::endl;
        }else{
            std::unordered_map<std::string, migraphx::argument> inputData;
            inputData[input_name] = migraphx::argument{input_shape, (float *)data};
            std::vector<migraphx::argument> results = net.eval(inputData);
            migraphx::argument result = results[0] ; //get output data  
            postprocess((float *)result.data(),boxes);
            std::cout<<"offload copy mode ..."<<std::endl;
        }
        
       
        float ratio_w = float(net_input_width) / float(img.cols);
        float ratio_h = float(net_input_height) / float(img.rows);
       
        text_roi_boxes = filter_det_res(boxes, ratio_h, ratio_w, img);
580
        // visualize_boxes(img,text_roi_boxes);
liuhy's avatar
liuhy committed
581
582
583
584
585
586
587
588
589
590
        return true;
    }
 
    CTCDecode::CTCDecode(std::string rec_model_path,
        std::string precision_mode,
        int image_width,
        int image_height,
        int channel,
        int batch_size,
        bool offload_copy,
591
        std::string character_dict_path){ 
liuhy's avatar
liuhy committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        if(!Exists(rec_model_path))
        {
            LOG_ERROR(stdout, "onnx file not exists!\n");
            exit(0);
        }
        this->batch_size = batch_size;
        this->net_input_width=image_width;
        this->net_input_height=image_height;
        this->net_input_channel=channel;
        this->precision_mode = precision_mode;

        migraphx::onnx_options onnx_options;
        onnx_options.map_input_dims["x"] = {1, 3, 48, 720};

        net = migraphx::parse_onnx(rec_model_path,onnx_options);
        LOG_INFO(stdout, "Succeed to load model: %s %s\n", GetFileName(rec_model_path).c_str(),this->precision_mode.c_str());

        if(this->precision_mode.compare("fp16")==0)
        {
            LOG_INFO(stdout, "Set precison mode: %s\n",this->precision_mode.c_str());
            migraphx::quantize_fp16(net);
        }

        std::unordered_map<std::string, migraphx::shape> inputs  = net.get_inputs();
        std::unordered_map<std::string, migraphx::shape> outputs = net.get_outputs();
        this->input_name   = inputs.begin()->first;
        this->input_shape  = inputs.begin()->second;
        this->output_name  = outputs.begin()->first;
        this->output_shape = outputs.begin()->second;

        int N            = this->input_shape.lens()[0];
        int C            = this->input_shape.lens()[1];
        int H            = this->input_shape.lens()[2];
        int W            = this->input_shape.lens()[3];
        
        data =(float*)malloc(N*C*H*W*sizeof(float));

        this->feature_size = output_shape.lens()[2];
        n_channel = this->output_shape.lens()[1];

        this->offload_copy = offload_copy;
        migraphx::compile_options options;
        options.device_id = 0; // default device cuda:0
        options.offload_copy = offload_copy;
        migraphx::target gpuTarget = migraphx::gpu::target{};
        net.compile(gpuTarget, options);

639
640
        float *warm_data = (float*)malloc(this->input_shape.bytes());
        memset(warm_data, 1.0, this->input_shape.bytes());
liuhy's avatar
liuhy committed
641
642
643
644
645
646
647
648
649
        if( this->offload_copy ==false )
        {
            hipMalloc(&input_buffer_device, this->input_shape.bytes());
            hipMalloc(&output_buffer_device, this->output_shape.bytes());
            output_buffer_host   =  (void*)malloc(this->output_shape.bytes());

            dev_argument[input_name]  = migraphx::argument{input_shape, input_buffer_device};
            dev_argument[output_name] = migraphx::argument{output_shape, output_buffer_device};

650
651
652
653
654
655
656
657
658
659
660
661
662
663
             hipMemcpy(input_buffer_device,
                  (void*)warm_data,
                  this->input_shape.bytes(),
                  hipMemcpyHostToDevice);
            //warm up
            std::vector<migraphx::argument> results = net.eval(dev_argument);
        }else{
            std::unordered_map<std::string, migraphx::argument> inputData;
            inputData[input_name] = migraphx::argument{input_shape, (float *)warm_data};
            //warm up
            std::vector<migraphx::argument> results = net.eval(inputData);
        }
        free(warm_data);
    
liuhy's avatar
liuhy committed
664
665
666
667
668
        std::ifstream infile; 
        infile.open(character_dict_path,std::ios::in);    
        assert(infile.is_open()); 
        std::string k_work=""; 
        k_words.clear();
669
        //读取字典文件
liuhy's avatar
liuhy committed
670
671
672
673
674
675
676
        while (std::getline(infile,k_work))
        {
            k_words.push_back(k_work);
        }
        system("chcp 65001");
    }

677
    CTCDecode::~CTCDecode(){
liuhy's avatar
liuhy committed
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        if(data)
        {
            free(data);
            data = nullptr;
        }

        if( offload_copy == false )
        {
            if(input_buffer_device)
            {
                hipFree(input_buffer_device);
            }
            if(output_buffer_device)
            {
                hipFree(output_buffer_device);
            }

            if(output_buffer_host)
            {
                free(output_buffer_host);
            }
        }
    }

702
    bool CTCDecode::preproc(cv::Mat img,float* data,int img_w,int img_h){
liuhy's avatar
liuhy committed
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
        if (img.empty())
        {
            std::cout<<"WARNING image is empty!\n";
            return false;
        }

        float scale=1.0/255.;
        int iw=img.cols;
        int ih=img.rows;
        float ratio=min(img_h*1.0/ih,img_w*1.0/iw);
        int nw=static_cast<int> (iw*ratio);
        int nh=img_h;
        cv::Mat res_mat;
        cv::resize(img,res_mat,cv::Size(nw,nh));
        cv::Mat template_mat=cv::Mat(img_h,img_w,CV_8UC3,cv::Scalar(0,0,0));
        int xdet=img_w-nw;
        int ydet=img_h-nh;
        cv::copyMakeBorder(res_mat, template_mat, 0,ydet, 0, xdet, 0); 
        memset(data,0.0,this->batch_size*3*img_w*img_h*sizeof(float));
      
        for(int b =0 ; b < this->batch_size;b++ )
        {
            for(int i=0;i<img_h;i++)
            {
                for(int j=0;j<img_w;j++)
                { 
                    data[i*img_w+j] = (template_mat.at<cv::Vec3b>(i, j)[2]*scale-0.5)/0.5;
                    data[i*img_w+j+img_h*img_w] = (template_mat.at<cv::Vec3b>(i, j)[1]*scale-0.5)/0.5;
                    data[i*img_w+j+2*img_h*img_w] =( template_mat.at<cv::Vec3b>(i, j)[0]*scale-0.5)/0.5;  
                }
            }
        }
        return  true ;
    }

738
    std::string CTCDecode::decode(std::vector<float>& probs,std::vector<int>& indexs,float& mean_prob){
liuhy's avatar
liuhy committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
        int ignored_tokens=0;
        std::string text="";
        std::vector<float> n_probs;
        std::vector<int> n_indexs;
        int eff_text_num=0;
    
        for (int i=0;i<n_channel;i++)
        {
            if(indexs[i]==ignored_tokens)
            {
                continue;
            }
            if(i>0 && indexs[i-1]==indexs[i])
            {
                continue;
            }

            mean_prob+=probs[i];
            text+=k_words[indexs[i]-1];
            eff_text_num++;
        }

        if(eff_text_num!=0)
        {
            mean_prob/=eff_text_num;
        }
        else
        {
            mean_prob = 0.;
        }
        
        return text;
    } 
liuhy's avatar
liuhy committed
772
    std::string CTCDecode::postprocess(float* feature){
liuhy's avatar
liuhy committed
773
774
775
776
777
778
779
780
781
782
783
784
785
        std::vector<float> probs;
        std::vector<int> indexs;
        float prob=0.;
        for (int i=0;i<n_channel;i++)
        {
            float* c_feat = feature+i*feature_size;
            int max_index = argmax<float*>(c_feat,c_feat+feature_size);
            float max_pro = c_feat[max_index];
            probs.push_back(max_pro);
            indexs.push_back(max_index);
        }
        
        std::string text = decode(probs,indexs,prob);
786
        std::cout<<"ocr res :"<<text<<"  "<<prob<<"\n";
liuhy's avatar
liuhy committed
787
788
789
790
        
        return text;
    }

791
    std::string  CTCDecode::forward(cv::Mat& img){
liuhy's avatar
liuhy committed
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
        preproc(img,data,net_input_width,net_input_height);
        if( this->offload_copy ==false )
        {
            hipMemcpy(input_buffer_device,
                  (void*)data,
                  this->input_shape.bytes(),
                  hipMemcpyHostToDevice);

            std::vector<migraphx::argument> results = net.eval(dev_argument);
          
            hipMemcpy(output_buffer_host,
            (void*)output_buffer_device,
            output_shape.bytes(),
            hipMemcpyDeviceToHost);
            std::string text = postprocess((float *)output_buffer_device);
            return text;
        }else{
            std::unordered_map<std::string, migraphx::argument> inputData;
            inputData[input_name] = migraphx::argument{input_shape, (float *)data};
            std::vector<migraphx::argument> results = net.eval(inputData);
            migraphx::argument result = results[0] ;  
            std::string text = postprocess((float *)result.data());
            return text;
        }
    }

    ppOcrEngine::ppOcrEngine(const std::string &det_model_path,
                    const std::string &rec_model_path,
                    const std::string &character_dict_path,
821
                    const std::string front,
liuhy's avatar
liuhy committed
822
823
824
                    float segm_thres,
                    float box_thresh,
                    bool offload_copy,
825
826
                    std::string precision_mode
                    ){
liuhy's avatar
liuhy committed
827
828
        text_detector = std::make_shared<OcrDet>(det_model_path,precision_mode,offload_copy,segm_thres,box_thresh);
        text_recognizer = std::make_shared<CTCDecode>(rec_model_path,precision_mode,720,48,3,1,offload_copy,character_dict_path);
829
        ft2 = std::make_shared<PutText>(front.c_str());
liuhy's avatar
liuhy committed
830
831
    }

832
    ppOcrEngine::~ppOcrEngine(){
liuhy's avatar
liuhy committed
833
834
835
        ;
    }
    
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
    void ppOcrEngine::visualize_boxes(cv::Mat &srcimg,
        const std::vector<std::vector<std::vector<int>>> &boxes) {
        std::vector<std::vector<cv::Point>> contours;
        for (const auto& box : boxes) {
            std::vector<cv::Point> pts;
            for (const auto& point : box) {
                pts.emplace_back(point[0], point[1]);
            }
            contours.push_back(pts);
        }
        cv::polylines(
            srcimg,
            contours,                 
            true,                    // 是否闭合
            cv::Scalar(0, 255, 0),   // 默认绿色
            2,                       // 线宽
            cv::LINE_8               // 8连通线
        );
    }

liuhy's avatar
liuhy committed
856
    cv::Mat ppOcrEngine::visualize_text(std::vector<std::string> texts,std::vector<cv::Point> points, cv::Mat &img){
857
858
859
860
861
862
863
864
865
866
867
868
869
        assert(texts.size()==points.size()),"error texts size != points size";
        cv::Mat draw_img = cv::Mat(img.size(), CV_8UC3,cv::Scalar(255,255,255));
        int width = img.cols*2;
        int height = img.rows;
        cv::Mat templete_img = cv::Mat(width,height, CV_8UC3,cv::Scalar(255,255,255));
        for(int i = 0 ; i < texts.size(); i++)
        {
            ft2->putText(draw_img,texts[i],points[i].x,points[i].y,15);
        }
        cv::hconcat(img, draw_img, templete_img);
        return templete_img;
    }
    std::vector<std::string> ppOcrEngine::forward(cv::Mat &srcimg){
liuhy's avatar
liuhy committed
870
        std::vector<std::vector<std::vector<int>>> text_roi_boxes;
871
         
liuhy's avatar
liuhy committed
872
873
874
875
876
877
878
879
        std::vector<std::string> text_vec;
        auto start = std::chrono::high_resolution_clock::now();
        text_detector->forward(srcimg,text_roi_boxes);
        if(text_roi_boxes.size() == 0)
        {
            std::cout<<"Not found text roi !\n";
            return std::vector<std::string>();
        }
880
881
       
        std::vector<cv::Point> points;
liuhy's avatar
liuhy committed
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
        for (int n = 0; n < text_roi_boxes.size(); n++) {
            
            cv::Rect rect;
            cv::Mat text_roi_mat;
            rect.x = text_roi_boxes[n][0][0];
            rect.y = text_roi_boxes[n][0][1];
            rect.width = text_roi_boxes[n][2][0] -  text_roi_boxes[n][0][0];
            rect.height = text_roi_boxes[n][2][1] - text_roi_boxes[n][0][1];
            if(rect.width <3 || rect.height<3)
            {
                continue;
            }
            text_roi_mat = srcimg(rect).clone();
            std::string text = text_recognizer->forward(text_roi_mat);
            text_vec.push_back(text);
897
            points.push_back(cv::Point(rect.x,rect.y));
liuhy's avatar
liuhy committed
898
899
900
        }  
        auto end = std::chrono::high_resolution_clock::now(); 
        auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
901
902
903
904
        std::cout<<"[Time info] elapsed: "<< duration_ms.count() <<" ms\n";
        visualize_boxes(srcimg,text_roi_boxes);
        cv::Mat res_img = visualize_text(text_vec,points, srcimg);
        cv::imwrite("res.jpg",res_img);
liuhy's avatar
liuhy committed
905
906
907
908
909
910
911
912
913
        return text_vec;
    }

}