OcrDB.cpp 17.8 KB
Newer Older
Your Name's avatar
Your Name committed
1
2
3
4
5
6
7
8
9
10
11
#include <OcrDB.h>
#include <migraphx/onnx.hpp>
#include <migraphx/gpu/target.hpp>
#include <Filesystem.h>
#include <SimpleLog.h>

using namespace cv::dnn;

namespace migraphxSamples
{

liucong's avatar
liucong committed
12
DB::DB() {}
Your Name's avatar
Your Name committed
13

liucong's avatar
liucong committed
14
DB::~DB() { configurationFile.release(); }
Your Name's avatar
Your Name committed
15
16
17

ErrorCode DB::Initialize(InitializationParameterOfDB InitializationParameterOfDB)
{
liucong's avatar
liucong committed
18
    // 读取配置文件
liucong's avatar
liucong committed
19
    std::string configFilePath = InitializationParameterOfDB.configFilePath;
liucong's avatar
liucong committed
20
    if(!Exists(configFilePath))
Your Name's avatar
Your Name committed
21
    {
liucong's avatar
liucong committed
22
23
        LOG_ERROR(stdout, "no configuration file!\n");
        return CONFIG_FILE_NOT_EXIST;
Your Name's avatar
Your Name committed
24
    }
liucong's avatar
liucong committed
25
26
    if(!configurationFile.open(configFilePath, cv::FileStorage::READ))
    {
liucong's avatar
liucong committed
27
28
        LOG_ERROR(stdout, "fail to open configuration file\n");
        return FAIL_TO_OPEN_CONFIG_FILE;
liucong's avatar
liucong committed
29
30
    }
    LOG_INFO(stdout, "succeed to open configuration file\n");
Your Name's avatar
Your Name committed
31
32

    // 获取配置文件参数
liucong's avatar
liucong committed
33
34
    cv::FileNode netNode        = configurationFile["OcrDB"];
    std::string modelPath       = (string)netNode["ModelPath"];
Your Name's avatar
Your Name committed
35
    dbParameter.BinaryThreshold = (float)netNode["BinaryThreshold"];
liucong's avatar
liucong committed
36
37
38
39
    dbParameter.BoxThreshold    = (float)netNode["BoxThreshold"];
    dbParameter.UnclipRatio     = (float)netNode["UnclipRatio"];
    dbParameter.LimitSideLen    = (int)netNode["LimitSideLen"];
    dbParameter.ScoreMode       = (string)netNode["ScoreMode"];
Your Name's avatar
Your Name committed
40
41

    // 加载模型
liucong's avatar
liucong committed
42
    if(!Exists(modelPath))
Your Name's avatar
Your Name committed
43
    {
liucong's avatar
liucong committed
44
        LOG_ERROR(stdout, "%s not exist!\n", modelPath.c_str());
Your Name's avatar
Your Name committed
45
46
47
        return MODEL_NOT_EXIST;
    }
    migraphx::onnx_options onnx_options;
liucong's avatar
liucong committed
48
49
50
    onnx_options.map_input_dims["x"] = {1, 3, 2496, 2496}; // 设置最大shape
    net                              = migraphx::parse_onnx(modelPath, onnx_options);
    LOG_INFO(stdout, "succeed to load model: %s\n", GetFileName(modelPath).c_str());
Your Name's avatar
Your Name committed
51

liucong's avatar
liucong committed
52
    // 获取模型输入/输出节点信息
liucong's avatar
liucong committed
53
54
55
56
57
58
59
60
61
    std::unordered_map<std::string, migraphx::shape> inputs  = net.get_inputs();
    std::unordered_map<std::string, migraphx::shape> outputs = net.get_outputs();
    inputName                                                = inputs.begin()->first;
    inputShape                                               = inputs.begin()->second;
    int N                                                    = inputShape.lens()[0];
    int C                                                    = inputShape.lens()[1];
    int H                                                    = inputShape.lens()[2];
    int W                                                    = inputShape.lens()[3];
    inputSize                                                = cv::Size(W, H);
Your Name's avatar
Your Name committed
62
63
64
65
66
67

    // 设置模型为GPU模式
    migraphx::target gpuTarget = migraphx::gpu::target{};

    // 编译模型
    migraphx::compile_options options;
liucong's avatar
liucong committed
68
69
70
71
    options.device_id    = 0; // 设置GPU设备,默认为0号设备
    options.offload_copy = true;
    net.compile(gpuTarget, options);
    LOG_INFO(stdout, "succeed to compile model: %s\n", GetFileName(modelPath).c_str());
Your Name's avatar
Your Name committed
72

liucong's avatar
liucong committed
73
74
    // warm up
    std::unordered_map<std::string, migraphx::argument> inputData;
liucong's avatar
liucong committed
75
    inputData[inputName] = migraphx::argument{inputShape};
liucong's avatar
liucong committed
76
    net.eval(inputData);
Your Name's avatar
Your Name committed
77
78

    // log
liucong's avatar
liucong committed
79
80
    LOG_INFO(stdout, "InputMaxSize:%dx%d\n", inputSize.width, inputSize.height);
    LOG_INFO(stdout, "InputName:%s\n", inputName.c_str());
Your Name's avatar
Your Name committed
81
82
83
84

    return SUCCESS;
}

liucong's avatar
liucong committed
85
ErrorCode DB::Infer(const cv::Mat& img, std::vector<cv::Mat>& imgList)
Your Name's avatar
Your Name committed
86
{
liucong's avatar
liucong committed
87
    if(img.empty() || img.type() != CV_8UC3)
Your Name's avatar
Your Name committed
88
    {
liucong's avatar
liucong committed
89
        LOG_ERROR(stdout, "image error!\n");
Your Name's avatar
Your Name committed
90
91
92
93
94
95
96
        return IMAGE_ERROR;
    }

    cv::Mat srcImage;
    cv::Mat resizeImg;
    img.copyTo(srcImage);

liucong's avatar
liucong committed
97
98
    int w       = srcImage.cols;
    int h       = srcImage.rows;
Your Name's avatar
Your Name committed
99
    float ratio = 1.f;
liucong's avatar
liucong committed
100
101
    int maxWH   = std::max(h, w);
    if(maxWH > dbParameter.LimitSideLen)
Your Name's avatar
Your Name committed
102
    {
liucong's avatar
liucong committed
103
        if(h > w)
Your Name's avatar
Your Name committed
104
105
106
107
108
109
110
        {
            ratio = float(dbParameter.LimitSideLen) / float(h);
        }
        else
        {
            ratio = float(dbParameter.LimitSideLen) / float(w);
        }
liucong's avatar
liucong committed
111
    }
Your Name's avatar
Your Name committed
112
113
114

    int resizeH = int(float(h) * ratio);
    int resizeW = int(float(w) * ratio);
liucong's avatar
liucong committed
115
116
    resizeH     = std::max(int(round(float(resizeH) / 32) * 32), 32);
    resizeW     = std::max(int(round(float(resizeW) / 32) * 32), 32);
Your Name's avatar
Your Name committed
117
118
119
120
121
    cv::resize(srcImage, resizeImg, cv::Size(resizeW, resizeH));

    float ratioH = float(resizeH) / float(h);
    float ratioW = float(resizeW) / float(w);

liucong's avatar
liucong committed
122
    resizeImg.convertTo(resizeImg, CV_32FC3, 1.0 / 255.0);
Your Name's avatar
Your Name committed
123
124
125
    std::vector<cv::Mat> bgrChannels(3);
    cv::split(resizeImg, bgrChannels);

liucong's avatar
liucong committed
126
    std::vector<float> mean  = {0.485f, 0.456f, 0.406f};
Your Name's avatar
Your Name committed
127
    std::vector<float> scale = {1 / 0.229f, 1 / 0.224f, 1 / 0.225f};
liucong's avatar
liucong committed
128
    for(auto i = 0; i < bgrChannels.size(); i++)
Your Name's avatar
Your Name committed
129
    {
liucong's avatar
liucong committed
130
131
        bgrChannels[i].convertTo(
            bgrChannels[i], CV_32FC1, 1.0 * scale[i], (0.0 - mean[i]) * scale[i]);
Your Name's avatar
Your Name committed
132
133
134
135
136
    }
    cv::merge(bgrChannels, resizeImg);
    int rh = resizeImg.rows;
    int rw = resizeImg.cols;
    cv::Mat inputBlob;
liucong's avatar
liucong committed
137
138
    inputBlob                                  = cv::dnn::blobFromImage(resizeImg);
    std::vector<std::size_t> inputShapeOfInfer = {1, 3, rh, rw};
Your Name's avatar
Your Name committed
139

liucong's avatar
liucong committed
140
141
    // 创建输入数据
    std::unordered_map<std::string, migraphx::argument> inputData;
liucong's avatar
liucong committed
142
143
    inputData[inputName] = migraphx::argument{migraphx::shape(inputShape.type(), inputShapeOfInfer),
                                              (float*)inputBlob.data};
Your Name's avatar
Your Name committed
144
145
146

    // 推理
    std::vector<migraphx::argument> inferenceResults = net.eval(inputData);
liucong's avatar
liucong committed
147

Your Name's avatar
Your Name committed
148
    // 获取推理结果
liucong's avatar
liucong committed
149
    migraphx::argument result = inferenceResults[0];
Your Name's avatar
Your Name committed
150
151
152

    // 转换为vector
    migraphx::shape outputShape = result.get_shape();
liucong's avatar
liucong committed
153
154
    int shape[]                 = {
        outputShape.lens()[0], outputShape.lens()[1], outputShape.lens()[2], outputShape.lens()[3]};
Your Name's avatar
Your Name committed
155
156
    int n2 = outputShape.lens()[2];
    int n3 = outputShape.lens()[3];
liucong's avatar
liucong committed
157
    int n  = n2 * n3;
Your Name's avatar
Your Name committed
158
    std::vector<float> out(n);
liucong's avatar
liucong committed
159
    memcpy(out.data(), result.data(), sizeof(float) * outputShape.elements());
Your Name's avatar
Your Name committed
160
    out.resize(n);
liucong's avatar
liucong committed
161

Your Name's avatar
Your Name committed
162
163
    std::vector<float> pred(n, 0.0);
    std::vector<unsigned char> cbuf(n, ' ');
liucong's avatar
liucong committed
164
    for(int i = 0; i < n; i++)
Your Name's avatar
Your Name committed
165
166
167
168
169
    {
        pred[i] = (float)(out[i]);
        cbuf[i] = (unsigned char)((out[i]) * 255);
    }

liucong's avatar
liucong committed
170
171
    cv::Mat cbufMap(n2, n3, CV_8UC1, (unsigned char*)cbuf.data());
    cv::Mat predMap(n2, n3, CV_32F, (float*)pred.data());
Your Name's avatar
Your Name committed
172
    const double threshold = dbParameter.BinaryThreshold * 255;
liucong's avatar
liucong committed
173
    const double maxvalue  = 255;
Your Name's avatar
Your Name committed
174
175
176
177
178
    cv::Mat bitMap;
    cv::threshold(cbufMap, bitMap, threshold, maxvalue, cv::THRESH_BINARY);

    std::vector<std::vector<std::vector<int>>> boxes;
    DBPostProcessor postProcessor;
liucong's avatar
liucong committed
179
180
    boxes = postProcessor.BoxesFromBitmap(
        predMap, bitMap, dbParameter.BoxThreshold, dbParameter.UnclipRatio, dbParameter.ScoreMode);
Your Name's avatar
Your Name committed
181
182
    boxes = postProcessor.FilterTagDetRes(boxes, ratioH, ratioW, srcImage);

liucong's avatar
liucong committed
183
184
    std::vector<migraphxSamples::OCRPredictResult> ocrResults;
    for(int i = 0; i < boxes.size(); i++)
Your Name's avatar
Your Name committed
185
186
187
188
189
190
191
    {
        OCRPredictResult res;
        res.box = boxes[i];
        ocrResults.push_back(res);
    }
    Utility::sorted_boxes(ocrResults);

liucong's avatar
liucong committed
192
    for(int j = 0; j < ocrResults.size(); j++)
Your Name's avatar
Your Name committed
193
194
195
196
197
    {
        cv::Mat cropImg;
        cropImg = Utility::GetRotateCropImage(img, ocrResults[j].box);
        imgList.push_back(cropImg);
    }
liucong's avatar
liucong committed
198
    return SUCCESS;
Your Name's avatar
Your Name committed
199
200
}

liucong's avatar
liucong committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
void DBPostProcessor::GetContourArea(const std::vector<std::vector<float>>& box,
                                     float unclip_ratio,
                                     float& distance)
{
    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;
Your Name's avatar
Your Name committed
218
219
220
}

cv::RotatedRect DBPostProcessor::UnClip(std::vector<std::vector<float>> box,
liucong's avatar
liucong committed
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
                                        const float& unclip_ratio)
{
    float distance = 1.0;

    GetContourArea(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);
Your Name's avatar
Your Name committed
254
    }
liucong's avatar
liucong committed
255
    return res;
Your Name's avatar
Your Name committed
256
257
}

liucong's avatar
liucong committed
258
259
260
261
262
263
264
265
266
267
268
float** DBPostProcessor::Mat2Vec(cv::Mat mat)
{
    auto** array = new float*[mat.rows];
    for(int i = 0; i < mat.rows; ++i)
        array[i] = new float[mat.cols];
    for(int i = 0; i < mat.rows; ++i)
    {
        for(int j = 0; j < mat.cols; ++j)
        {
            array[i][j] = mat.at<float>(i, j);
        }
Your Name's avatar
Your Name committed
269
270
    }

liucong's avatar
liucong committed
271
    return array;
Your Name's avatar
Your Name committed
272
273
274
}

std::vector<std::vector<int>>
liucong's avatar
liucong committed
275
276
277
278
DBPostProcessor::OrderPointsClockwise(std::vector<std::vector<int>> pts)
{
    std::vector<std::vector<int>> box = pts;
    std::sort(box.begin(), box.end(), XsortInt);
Your Name's avatar
Your Name committed
279

liucong's avatar
liucong committed
280
281
    std::vector<std::vector<int>> leftmost  = {box[0], box[1]};
    std::vector<std::vector<int>> rightmost = {box[2], box[3]};
Your Name's avatar
Your Name committed
282

liucong's avatar
liucong committed
283
284
    if(leftmost[0][1] > leftmost[1][1])
        std::swap(leftmost[0], leftmost[1]);
Your Name's avatar
Your Name committed
285

liucong's avatar
liucong committed
286
287
    if(rightmost[0][1] > rightmost[1][1])
        std::swap(rightmost[0], rightmost[1]);
Your Name's avatar
Your Name committed
288

liucong's avatar
liucong committed
289
290
    std::vector<std::vector<int>> rect = {leftmost[0], rightmost[0], rightmost[1], leftmost[1]};
    return rect;
Your Name's avatar
Your Name committed
291
292
}

liucong's avatar
liucong committed
293
294
295
296
std::vector<std::vector<float>> DBPostProcessor::Mat2Vector(cv::Mat mat)
{
    std::vector<std::vector<float>> img_vec;
    std::vector<float> tmp;
Your Name's avatar
Your Name committed
297

liucong's avatar
liucong committed
298
299
300
301
302
303
304
305
    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);
Your Name's avatar
Your Name committed
306
    }
liucong's avatar
liucong committed
307
    return img_vec;
Your Name's avatar
Your Name committed
308
309
}

liucong's avatar
liucong committed
310
311
312
313
314
bool DBPostProcessor::XsortFp32(std::vector<float> a, std::vector<float> b)
{
    if(a[0] != b[0])
        return a[0] < b[0];
    return false;
Your Name's avatar
Your Name committed
315
316
}

liucong's avatar
liucong committed
317
318
319
320
321
bool DBPostProcessor::XsortInt(std::vector<int> a, std::vector<int> b)
{
    if(a[0] != b[0])
        return a[0] < b[0];
    return false;
Your Name's avatar
Your Name committed
322
323
}

liucong's avatar
liucong committed
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
std::vector<std::vector<float>> DBPostProcessor::GetMiniBoxes(cv::RotatedRect box, float& ssid)
{
    ssid = std::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;
Your Name's avatar
Your Name committed
362
363
}

liucong's avatar
liucong committed
364
365
366
367
368
369
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
float DBPostProcessor::PolygonScoreAcc(std::vector<cv::Point> contour, cv::Mat pred)
{
    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;
Your Name's avatar
Your Name committed
404
405
}

liucong's avatar
liucong committed
406
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
436
float DBPostProcessor::BoxScoreFast(std::vector<std::vector<float>> box_array, cv::Mat pred)
{
    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;
Your Name's avatar
Your Name committed
437
438
}

liucong's avatar
liucong committed
439
440
441
442
443
444
445
446
447
std::vector<std::vector<std::vector<int>>>
DBPostProcessor::BoxesFromBitmap(const cv::Mat pred,
                                 const cv::Mat bitmap,
                                 const float& box_thresh,
                                 const float& det_db_unclip_ratio,
                                 const std::string& det_db_score_mode)
{
    const int min_size       = 3;
    const int max_candidates = 2000;
Your Name's avatar
Your Name committed
448

liucong's avatar
liucong committed
449
450
    int width  = bitmap.cols;
    int height = bitmap.rows;
Your Name's avatar
Your Name committed
451

liucong's avatar
liucong committed
452
453
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;
Your Name's avatar
Your Name committed
454

liucong's avatar
liucong committed
455
    cv::findContours(bitmap, contours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
Your Name's avatar
Your Name committed
456

liucong's avatar
liucong committed
457
    int num_contours = contours.size() >= max_candidates ? max_candidates : contours.size();
Your Name's avatar
Your Name committed
458

liucong's avatar
liucong committed
459
    std::vector<std::vector<std::vector<int>>> boxes;
Your Name's avatar
Your Name committed
460

liucong's avatar
liucong committed
461
462
463
464
465
466
467
468
469
    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          = GetMiniBoxes(box, ssid);
Your Name's avatar
Your Name committed
470

liucong's avatar
liucong committed
471
472
        auto box_for_unclip = array;
        // end get_mini_box
Your Name's avatar
Your Name committed
473

liucong's avatar
liucong committed
474
475
476
477
        if(ssid < min_size)
        {
            continue;
        }
Your Name's avatar
Your Name committed
478

liucong's avatar
liucong committed
479
480
481
482
483
484
        float score;
        if(det_db_score_mode == "slow")
            /* compute using polygon*/
            score = PolygonScoreAcc(contours[_i], pred);
        else
            score = BoxScoreFast(array, pred);
Your Name's avatar
Your Name committed
485

liucong's avatar
liucong committed
486
487
        if(score < box_thresh)
            continue;
Your Name's avatar
Your Name committed
488

liucong's avatar
liucong committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
        // start for unclip
        cv::RotatedRect points = UnClip(box_for_unclip, det_db_unclip_ratio);
        if(points.size.height < 1.001 && points.size.width < 1.001)
        {
            continue;
        }
        // end for unclip

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

        if(ssid < min_size + 2)
            continue;

        int dest_width  = pred.cols;
        int dest_height = pred.rows;
        std::vector<std::vector<int>> intcliparray;
Your Name's avatar
Your Name committed
506

liucong's avatar
liucong committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
        for(int num_pt = 0; num_pt < 4; num_pt++)
        {
            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);
        }
        boxes.push_back(intcliparray);

    } // end for
    return boxes;
Your Name's avatar
Your Name committed
522
523
524
}

std::vector<std::vector<std::vector<int>>> DBPostProcessor::FilterTagDetRes(
liucong's avatar
liucong committed
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
    std::vector<std::vector<std::vector<int>>> boxes, float ratio_h, float ratio_w, cv::Mat srcimg)
{
    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] = OrderPointsClockwise(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]);
Your Name's avatar
Your Name committed
554
    }
liucong's avatar
liucong committed
555
    return root_points;
Your Name's avatar
Your Name committed
556
557
}

liucong's avatar
liucong committed
558
} // namespace migraphxSamples