postprocess_op.cpp 17.9 KB
Newer Older
littletomatodonkey's avatar
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
#include <include/clipper.h>
littletomatodonkey's avatar
littletomatodonkey 已提交
16 17 18 19
#include <include/postprocess_op.h>

namespace PaddleOCR {

文幕地方's avatar
文幕地方 已提交
20 21
void DBPostProcessor::GetContourArea(const std::vector<std::vector<float>> &box,
                                     float unclip_ratio, float &distance) {
littletomatodonkey's avatar
littletomatodonkey 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
  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;
}

文幕地方's avatar
文幕地方 已提交
38 39
cv::RotatedRect DBPostProcessor::UnClip(std::vector<std::vector<float>> box,
                                        const float &unclip_ratio) {
littletomatodonkey's avatar
littletomatodonkey 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
  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);
    }
  }
61 62 63 64 65 66
  cv::RotatedRect res;
  if (points.size() <= 0) {
    res = cv::RotatedRect(cv::Point2f(0, 0), cv::Size2f(1, 1), 0);
  } else {
    res = cv::minAreaRect(points);
  }
littletomatodonkey's avatar
littletomatodonkey 已提交
67 68 69
  return res;
}

文幕地方's avatar
文幕地方 已提交
70
float **DBPostProcessor::Mat2Vec(cv::Mat mat) {
littletomatodonkey's avatar
littletomatodonkey 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83
  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);
    }
  }

  return array;
}

std::vector<std::vector<int>>
文幕地方's avatar
文幕地方 已提交
84
DBPostProcessor::OrderPointsClockwise(std::vector<std::vector<int>> pts) {
littletomatodonkey's avatar
littletomatodonkey 已提交
85
  std::vector<std::vector<int>> box = pts;
littletomatodonkey's avatar
littletomatodonkey 已提交
86 87
  std::sort(box.begin(), box.end(), XsortInt);

littletomatodonkey's avatar
littletomatodonkey 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101
  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;
}

文幕地方's avatar
文幕地方 已提交
102
std::vector<std::vector<float>> DBPostProcessor::Mat2Vector(cv::Mat mat) {
littletomatodonkey's avatar
littletomatodonkey 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115
  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;
}

文幕地方's avatar
文幕地方 已提交
116
bool DBPostProcessor::XsortFp32(std::vector<float> a, std::vector<float> b) {
littletomatodonkey's avatar
littletomatodonkey 已提交
117 118 119 120 121
  if (a[0] != b[0])
    return a[0] < b[0];
  return false;
}

文幕地方's avatar
文幕地方 已提交
122
bool DBPostProcessor::XsortInt(std::vector<int> a, std::vector<int> b) {
littletomatodonkey's avatar
littletomatodonkey 已提交
123 124 125 126 127
  if (a[0] != b[0])
    return a[0] < b[0];
  return false;
}

文幕地方's avatar
文幕地方 已提交
128 129
std::vector<std::vector<float>>
DBPostProcessor::GetMiniBoxes(cv::RotatedRect box, float &ssid) {
littletomatodonkey's avatar
littletomatodonkey 已提交
130
  ssid = std::max(box.size.width, box.size.height);
littletomatodonkey's avatar
littletomatodonkey 已提交
131 132 133 134

  cv::Mat points;
  cv::boxPoints(box, points);

littletomatodonkey's avatar
littletomatodonkey 已提交
135 136 137 138 139
  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];
littletomatodonkey's avatar
littletomatodonkey 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  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;
}

文幕地方's avatar
文幕地方 已提交
163 164
float DBPostProcessor::PolygonScoreAcc(std::vector<cv::Point> contour,
                                       cv::Mat pred) {
165 166 167 168
  int width = pred.cols;
  int height = pred.rows;
  std::vector<float> box_x;
  std::vector<float> box_y;
169
  for (int i = 0; i < contour.size(); ++i) {
170 171 172 173
    box_x.push_back(contour[i].x);
    box_y.push_back(contour[i].y);
  }

174 175 176 177 178 179 180 181 182 183 184 185
  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);
186 187 188 189

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

190
  cv::Point *rook_point = new cv::Point[contour.size()];
191

192
  for (int i = 0; i < contour.size(); ++i) {
193 194 195 196
    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())};
197

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

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

205
  delete[] rook_point;
206 207 208
  return score;
}

文幕地方's avatar
文幕地方 已提交
209 210
float DBPostProcessor::BoxScoreFast(std::vector<std::vector<float>> box_array,
                                    cv::Mat pred) {
littletomatodonkey's avatar
littletomatodonkey 已提交
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
  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;
}

文幕地方's avatar
文幕地方 已提交
247
std::vector<std::vector<std::vector<int>>> DBPostProcessor::BoxesFromBitmap(
248
    const cv::Mat pred, const cv::Mat bitmap, const float &box_thresh,
249
    const float &det_db_unclip_ratio, const std::string &det_db_score_mode) {
littletomatodonkey's avatar
littletomatodonkey 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  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++) {
littletomatodonkey's avatar
littletomatodonkey 已提交
268
    if (contours[_i].size() <= 2) {
269 270
      continue;
    }
littletomatodonkey's avatar
littletomatodonkey 已提交
271 272
    float ssid;
    cv::RotatedRect box = cv::minAreaRect(contours[_i]);
littletomatodonkey's avatar
littletomatodonkey 已提交
273
    auto array = GetMiniBoxes(box, ssid);
littletomatodonkey's avatar
littletomatodonkey 已提交
274 275 276 277 278 279 280 281 282

    auto box_for_unclip = array;
    // end get_mini_box

    if (ssid < min_size) {
      continue;
    }

    float score;
283
    if (det_db_score_mode == "slow")
284 285 286 287 288
      /* compute using polygon*/
      score = PolygonScoreAcc(contours[_i], pred);
    else
      score = BoxScoreFast(array, pred);

littletomatodonkey's avatar
littletomatodonkey 已提交
289 290 291 292
    if (score < box_thresh)
      continue;

    // start for unclip
littletomatodonkey's avatar
littletomatodonkey 已提交
293
    cv::RotatedRect points = UnClip(box_for_unclip, det_db_unclip_ratio);
294 295 296
    if (points.size.height < 1.001 && points.size.width < 1.001) {
      continue;
    }
littletomatodonkey's avatar
littletomatodonkey 已提交
297 298 299
    // end for unclip

    cv::RotatedRect clipbox = points;
littletomatodonkey's avatar
littletomatodonkey 已提交
300
    auto cliparray = GetMiniBoxes(clipbox, ssid);
littletomatodonkey's avatar
littletomatodonkey 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

    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++) {
      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;
}

文幕地方's avatar
文幕地方 已提交
324 325 326
std::vector<std::vector<std::vector<int>>> DBPostProcessor::FilterTagDetRes(
    std::vector<std::vector<std::vector<int>>> boxes, float ratio_h,
    float ratio_w, cv::Mat srcimg) {
littletomatodonkey's avatar
littletomatodonkey 已提交
327 328 329 330 331
  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++) {
littletomatodonkey's avatar
littletomatodonkey 已提交
332
    boxes[n] = OrderPointsClockwise(boxes[n]);
littletomatodonkey's avatar
littletomatodonkey 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    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)));
Z
zhoujun 已提交
348
    if (rect_width <= 4 || rect_height <= 4)
littletomatodonkey's avatar
littletomatodonkey 已提交
349 350 351 352 353 354
      continue;
    root_points.push_back(boxes[n]);
  }
  return root_points;
}

文幕地方's avatar
文幕地方 已提交
355 356 357 358 359
void TablePostProcessor::Run(
    std::vector<float> &loc_preds, std::vector<float> &structure_probs,
    std::vector<float> &rec_scores, std::vector<int> &loc_preds_shape,
    std::vector<int> &structure_probs_shape,
    std::vector<std::vector<std::string>> &rec_html_tag_batch,
文幕地方's avatar
文幕地方 已提交
360
    std::vector<std::vector<std::vector<int>>> &rec_boxes_batch,
文幕地方's avatar
文幕地方 已提交
361 362 363 364
    std::vector<int> &width_list, std::vector<int> &height_list) {
  for (int batch_idx = 0; batch_idx < structure_probs_shape[0]; batch_idx++) {
    // image tags and boxs
    std::vector<std::string> rec_html_tags;
文幕地方's avatar
文幕地方 已提交
365
    std::vector<std::vector<int>> rec_boxes;
文幕地方's avatar
文幕地方 已提交
366 367 368 369 370 371 372 373 374

    float score = 0.f;
    int count = 0;
    float char_score = 0.f;
    int char_idx = 0;

    // step
    for (int step_idx = 0; step_idx < structure_probs_shape[1]; step_idx++) {
      std::string html_tag;
文幕地方's avatar
文幕地方 已提交
375
      std::vector<int> rec_box;
文幕地方's avatar
文幕地方 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      // html tag
      int step_start_idx = (batch_idx * structure_probs_shape[1] + step_idx) *
                           structure_probs_shape[2];
      char_idx = int(Utility::argmax(
          &structure_probs[step_start_idx],
          &structure_probs[step_start_idx + structure_probs_shape[2]]));
      char_score = float(*std::max_element(
          &structure_probs[step_start_idx],
          &structure_probs[step_start_idx + structure_probs_shape[2]]));
      html_tag = this->label_list_[char_idx];

      if (step_idx > 0 && html_tag == this->end) {
        break;
      }
      if (html_tag == this->beg) {
        continue;
      }
      count += 1;
      score += char_score;
      rec_html_tags.push_back(html_tag);
文幕地方's avatar
文幕地方 已提交
396

文幕地方's avatar
文幕地方 已提交
397
      // box
文幕地方's avatar
文幕地方 已提交
398
      if (html_tag == "<td>" || html_tag == "<td" || html_tag == "<td></td>") {
文幕地方's avatar
文幕地方 已提交
399
        for (int point_idx = 0; point_idx < loc_preds_shape[2]; point_idx++) {
文幕地方's avatar
文幕地方 已提交
400 401 402
          step_start_idx = (batch_idx * structure_probs_shape[1] + step_idx) *
                               loc_preds_shape[2] +
                           point_idx;
文幕地方's avatar
文幕地方 已提交
403 404 405 406 407 408
          float point = loc_preds[step_start_idx];
          if (point_idx % 2 == 0) {
            point = int(point * width_list[batch_idx]);
          } else {
            point = int(point * height_list[batch_idx]);
          }
文幕地方's avatar
文幕地方 已提交
409 410 411 412 413 414
          rec_box.push_back(point);
        }
        rec_boxes.push_back(rec_box);
      }
    }
    score /= count;
文幕地方's avatar
文幕地方 已提交
415
    if (isnan(score) || rec_boxes.size() == 0) {
文幕地方's avatar
文幕地方 已提交
416 417 418 419 420 421 422 423
      score = -1;
    }
    rec_scores.push_back(score);
    rec_boxes_batch.push_back(rec_boxes);
    rec_html_tag_batch.push_back(rec_html_tags);
  }
}

文幕地方's avatar
文幕地方 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 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 547 548
void PicodetPostProcessor::Run(std::vector<StructurePredictResult> &results,
                               std::vector<std::vector<float>> outs,
                               std::vector<int> ori_shape,
                               std::vector<int> resize_shape, int reg_max) {
  int in_h = resize_shape[0];
  int in_w = resize_shape[1];
  float scale_factor_h = resize_shape[0] / float(ori_shape[0]);
  float scale_factor_w = resize_shape[1] / float(ori_shape[1]);

  std::vector<std::vector<StructurePredictResult>> bbox_results;
  bbox_results.resize(this->num_class_);
  for (int i = 0; i < this->fpn_stride_.size(); ++i) {
    int feature_h = std::ceil((float)in_h / this->fpn_stride_[i]);
    int feature_w = std::ceil((float)in_w / this->fpn_stride_[i]);
    for (int idx = 0; idx < feature_h * feature_w; idx++) {
      // score and label
      float score = 0;
      int cur_label = 0;
      for (int label = 0; label < this->num_class_; label++) {
        if (outs[i][idx * this->num_class_ + label] > score) {
          score = outs[i][idx * this->num_class_ + label];
          cur_label = label;
        }
      }
      // bbox
      if (score > this->score_threshold_) {
        int row = idx / feature_w;
        int col = idx % feature_w;
        std::vector<float> bbox_pred(
            outs[i + this->fpn_stride_.size()].begin() + idx * 4 * reg_max,
            outs[i + this->fpn_stride_.size()].begin() +
                (idx + 1) * 4 * reg_max);
        bbox_results[cur_label].push_back(
            this->disPred2Bbox(bbox_pred, cur_label, score, col, row,
                               this->fpn_stride_[i], resize_shape, reg_max));
      }
    }
  }
  for (int i = 0; i < bbox_results.size(); i++) {
    bool flag = bbox_results[i].size() <= 0;
  }
  for (int i = 0; i < bbox_results.size(); i++) {
    bool flag = bbox_results[i].size() <= 0;
    if (bbox_results[i].size() <= 0) {
      continue;
    }
    this->nms(bbox_results[i], this->nms_threshold_);
    for (auto box : bbox_results[i]) {
      box.box_float[0] = box.box_float[0] / scale_factor_w;
      box.box_float[2] = box.box_float[2] / scale_factor_w;
      box.box_float[1] = box.box_float[1] / scale_factor_h;
      box.box_float[3] = box.box_float[3] / scale_factor_h;
      box.box = {(int)box.box_float[0], (int)box.box_float[1],
                 (int)box.box_float[2], (int)box.box_float[3]};
      results.push_back(box);
    }
  }
}

StructurePredictResult
PicodetPostProcessor::disPred2Bbox(std::vector<float> bbox_pred, int label,
                                   float score, int x, int y, int stride,
                                   std::vector<int> im_shape, int reg_max) {
  float ct_x = (x + 0.5) * stride;
  float ct_y = (y + 0.5) * stride;
  std::vector<float> dis_pred;
  dis_pred.resize(4);
  for (int i = 0; i < 4; i++) {
    float dis = 0;
    std::vector<float> bbox_pred_i(bbox_pred.begin() + i * reg_max,
                                   bbox_pred.begin() + (i + 1) * reg_max);
    std::vector<float> dis_after_sm =
        Utility::activation_function_softmax(bbox_pred_i);
    for (int j = 0; j < reg_max; j++) {
      dis += j * dis_after_sm[j];
    }
    dis *= stride;
    dis_pred[i] = dis;
  }

  float xmin_float = (std::max)(ct_x - dis_pred[0], .0f);
  float ymin_float = (std::max)(ct_y - dis_pred[1], .0f);
  float xmax_float = (std::min)(ct_x + dis_pred[2], (float)im_shape[1]);
  float ymax_float = (std::min)(ct_y + dis_pred[3], (float)im_shape[0]);

  StructurePredictResult result_item;
  result_item.box_float = {xmin_float, ymin_float, xmax_float, ymax_float};
  result_item.type = this->label_list_[label];
  result_item.confidence = score;

  return result_item;
}

void PicodetPostProcessor::nms(std::vector<StructurePredictResult> &input_boxes,
                               float nms_threshold) {
  std::sort(input_boxes.begin(), input_boxes.end(),
            [](StructurePredictResult a, StructurePredictResult b) {
              return a.confidence > b.confidence;
            });
  std::vector<int> picked(input_boxes.size(), 1);

  for (int i = 0; i < input_boxes.size(); ++i) {
    if (picked[i] == 0) {
      continue;
    }
    for (int j = i + 1; j < input_boxes.size(); ++j) {
      if (picked[j] == 0) {
        continue;
      }
      float iou =
          Utility::iou(input_boxes[i].box_float, input_boxes[j].box_float);
      if (iou > nms_threshold) {
        picked[j] = 0;
      }
    }
  }
  std::vector<StructurePredictResult> input_boxes_nms;
  for (int i = 0; i < input_boxes.size(); ++i) {
    if (picked[i] == 1) {
      input_boxes_nms.push_back(input_boxes[i]);
    }
  }
  input_boxes = input_boxes_nms;
}

littletomatodonkey's avatar
littletomatodonkey 已提交
549
} // namespace PaddleOCR