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
14
15
16
17
18
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
54
55
#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>
inline size_t argmax(ForwardIterator first, ForwardIterator last)
{
    return std::distance(first, std::max_element(first, last));
}

static float sigmoid(float x)
{
    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;
    }
56
namespace ppocr{
liuhy's avatar
liuhy committed
57
58
59
60
    OcrDet::OcrDet(const std::string det_model_path,
            std::string precision_mode,
            bool offload_copy,
            float segm_thres,
61
            float box_thresh ){
liuhy's avatar
liuhy committed
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
117
118
       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);
119
120
121

        float *warm_data = (float*)malloc(this->input_shape.bytes());
        memset(warm_data, 1.0, this->input_shape.bytes());
liuhy's avatar
liuhy committed
122
123
124
125
126
127
128
129
130
        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};

131
132
133
134
135
136
137
138
139
140
141
142
143
             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
144
145
    }

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

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

171
    cv::Size OcrDet::preproc(cv::Mat img,float* data){
liuhy's avatar
liuhy committed
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
199
200
        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 ;
    }
    
201
    std::vector<std::vector<float>> OcrDet::get_mini_boxes(cv::RotatedRect box,float &ssid) {
liuhy's avatar
liuhy committed
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
268
269
        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)
270
271
                //多边形区域的平均得分作为box的分数
                score = polygon_score_acc(contours[_i], pred);
liuhy's avatar
liuhy committed
272
            else
273
             score = box_score_fast(array, pred);
liuhy's avatar
liuhy committed
274
275

            if (score < box_thresh)
276
                continue;
liuhy's avatar
liuhy committed
277

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

            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++) {
295
296
297
298
299
300
301
                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
302
303
304
            }
            boxes.push_back(intcliparray);

305
        }
liuhy's avatar
liuhy committed
306
307
308
        return boxes;
    }

309
    std::vector<std::vector<float>> OcrDet::Mat2Vector(cv::Mat mat){
liuhy's avatar
liuhy committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        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,
324
                                     cv::Mat pred){
liuhy's avatar
liuhy committed
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
369
370
        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,
371
                                  cv::Mat pred) {
liuhy's avatar
liuhy committed
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
406
407
        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,
408
                                      const float &unclip_ratio){
liuhy's avatar
liuhy committed
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
436
437
        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,
438
                                   float unclip_ratio, float &distance) {
liuhy's avatar
liuhy committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
        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,
456
                                float ratio_h, float ratio_w, cv::Mat srcimg){
liuhy's avatar
liuhy committed
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
483
484
        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;
    }
    
485
    std::vector<std::vector<int>> OcrDet::order_points_clockwise(std::vector<std::vector<int>> pts){
liuhy's avatar
liuhy committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
        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,
503
        const std::vector<std::vector<std::vector<int>>> &boxes){
liuhy's avatar
liuhy committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
        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;
    }
523
    int OcrDet::postprocess(float* feature, std::vector<std::vector<std::vector<int>>> &boxes){
liuhy's avatar
liuhy committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
        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;        
    }

549
    bool OcrDet::forward(cv::Mat& img,std::vector<std::vector<std::vector<int>>>& text_roi_boxes){
liuhy's avatar
liuhy committed
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
580
581
        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);
582
        // visualize_boxes(img,text_roi_boxes);
liuhy's avatar
liuhy committed
583
584
585
586
587
588
589
590
591
592
        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,
593
        std::string character_dict_path){ 
liuhy's avatar
liuhy committed
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
639
640
        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);

641
642
        float *warm_data = (float*)malloc(this->input_shape.bytes());
        memset(warm_data, 1.0, this->input_shape.bytes());
liuhy's avatar
liuhy committed
643
644
645
646
647
648
649
650
651
        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};

652
653
654
655
656
657
658
659
660
661
662
663
664
665
             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
666
667
668
669
670
        std::ifstream infile; 
        infile.open(character_dict_path,std::ios::in);    
        assert(infile.is_open()); 
        std::string k_work=""; 
        k_words.clear();
671
        //读取字典文件
liuhy's avatar
liuhy committed
672
673
674
675
676
677
678
        while (std::getline(infile,k_work))
        {
            k_words.push_back(k_work);
        }
        system("chcp 65001");
    }

679
    CTCDecode::~CTCDecode(){
liuhy's avatar
liuhy committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        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);
            }
        }
    }

704
    bool CTCDecode::preproc(cv::Mat img,float* data,int img_w,int img_h){
liuhy's avatar
liuhy committed
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
738
739
        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 ;
    }

740
    std::string CTCDecode::decode(std::vector<float>& probs,std::vector<int>& indexs,float& mean_prob){
liuhy's avatar
liuhy committed
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
        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;
    } 
    std::string CTCDecode::postprocess(float* feature)
    {
        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);
789
        std::cout<<"ocr res :"<<text<<"  "<<prob<<"\n";
liuhy's avatar
liuhy committed
790
791
792
793
        
        return text;
    }

794
    std::string  CTCDecode::forward(cv::Mat& img){
liuhy's avatar
liuhy committed
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
821
822
823
        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,
824
                    const std::string front,
liuhy's avatar
liuhy committed
825
826
827
                    float segm_thres,
                    float box_thresh,
                    bool offload_copy,
828
829
                    std::string precision_mode
                    ){
liuhy's avatar
liuhy committed
830
831
        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);
832
        ft2 = std::make_shared<PutText>(front.c_str());
liuhy's avatar
liuhy committed
833
834
    }

835
    ppOcrEngine::~ppOcrEngine(){
liuhy's avatar
liuhy committed
836
837
838
        ;
    }
    
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
    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连通线
        );
    }

    cv::Mat ppOcrEngine::visualize_text(std::vector<std::string> texts,std::vector<cv::Point> points, cv::Mat &img)
liuhy's avatar
liuhy committed
860
    {
861
862
863
864
865
866
867
868
869
870
871
872
873
        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
874
        std::vector<std::vector<std::vector<int>>> text_roi_boxes;
875
         
liuhy's avatar
liuhy committed
876
877
878
879
880
881
882
883
        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>();
        }
884
885
       
        std::vector<cv::Point> points;
liuhy's avatar
liuhy committed
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
        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);
901
            points.push_back(cv::Point(rect.x,rect.y));
liuhy's avatar
liuhy committed
902
903
904
        }  
        auto end = std::chrono::high_resolution_clock::now(); 
        auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
905
906
907
908
        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
909
910
911
912
913
914
915
916
917
        return text_vec;
    }

}