"examples/tool_chat_template_llama3.2_pythonic.jinja" did not exist on "e6dcd9bd508da5e3d14ac000eb2398933c872774"
db_post_process.cc 9.33 KB
Newer Older
LDOUVLEV's avatar
LDOUVLEV committed
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.

LDOUBLEV's avatar
LDOUBLEV committed
15
#include "db_post_process.h" // NOLINT
LDOUVLEV's avatar
LDOUVLEV committed
16
17
18
#include <algorithm>
#include <utility>

LDOUBLEV's avatar
LDOUBLEV committed
19
20
void GetContourArea(std::vector<std::vector<float>> box, float unclip_ratio,
                    float &distance) {
LDOUVLEV's avatar
LDOUVLEV committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  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;
}

cv::RotatedRect Unclip(std::vector<std::vector<float>> box,
                       float unclip_ratio) {
  float distance = 1.0;

  GetContourArea(box, unclip_ratio, distance);

  ClipperLib::ClipperOffset offset;
  ClipperLib::Path p;
LDOUBLEV's avatar
LDOUBLEV committed
45
46
47
48
49
50
51
52
  p << ClipperLib::IntPoint(static_cast<int>(box[0][0]),
                            static_cast<int>(box[0][1]))
    << ClipperLib::IntPoint(static_cast<int>(box[1][0]),
                            static_cast<int>(box[1][1]))
    << ClipperLib::IntPoint(static_cast<int>(box[2][0]),
                            static_cast<int>(box[2][1]))
    << ClipperLib::IntPoint(static_cast<int>(box[3][0]),
                            static_cast<int>(box[3][1]));
LDOUVLEV's avatar
LDOUVLEV committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  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 = cv::minAreaRect(points);

  return res;
}

std::vector<std::vector<float>> Mat2Vector(cv::Mat mat) {
  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;
}

bool XsortFp32(std::vector<float> a, std::vector<float> b) {
LDOUBLEV's avatar
LDOUBLEV committed
84
85
  if (a[0] != b[0])
    return a[0] < b[0];
LDOUVLEV's avatar
LDOUVLEV committed
86
87
88
89
  return false;
}

bool XsortInt(std::vector<int> a, std::vector<int> b) {
LDOUBLEV's avatar
LDOUBLEV committed
90
91
  if (a[0] != b[0])
    return a[0] < b[0];
LDOUVLEV's avatar
LDOUVLEV committed
92
93
94
  return false;
}

LDOUBLEV's avatar
LDOUBLEV committed
95
96
std::vector<std::vector<int>>
OrderPointsClockwise(std::vector<std::vector<int>> pts) {
LDOUVLEV's avatar
LDOUVLEV committed
97
98
99
100
101
102
  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]};

LDOUBLEV's avatar
LDOUBLEV committed
103
104
  if (leftmost[0][1] > leftmost[1][1])
    std::swap(leftmost[0], leftmost[1]);
LDOUVLEV's avatar
LDOUVLEV committed
105

LDOUBLEV's avatar
LDOUBLEV committed
106
107
  if (rightmost[0][1] > rightmost[1][1])
    std::swap(rightmost[0], rightmost[1]);
LDOUVLEV's avatar
LDOUVLEV committed
108

LDOUBLEV's avatar
LDOUBLEV committed
109
110
  std::vector<std::vector<int>> rect = {leftmost[0], rightmost[0], rightmost[1],
                                        leftmost[1]};
LDOUVLEV's avatar
LDOUVLEV committed
111
112
113
  return rect;
}

LDOUBLEV's avatar
LDOUBLEV committed
114
115
std::vector<std::vector<float>> GetMiniBoxes(cv::RotatedRect box, float &ssid) {
  ssid = std::max(box.size.width, box.size.height);
LDOUVLEV's avatar
LDOUVLEV committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

  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;
}

float 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]};

LDOUBLEV's avatar
LDOUBLEV committed
156
157
158
159
160
161
162
163
164
165
166
167
  int xmin = clamp(
      static_cast<int>(std::floorf(*(std::min_element(box_x, box_x + 4)))), 0,
      width - 1);
  int xmax =
      clamp(static_cast<int>(std::ceilf(*(std::max_element(box_x, box_x + 4)))),
            0, width - 1);
  int ymin = clamp(
      static_cast<int>(std::floorf(*(std::min_element(box_y, box_y + 4)))), 0,
      height - 1);
  int ymax =
      clamp(static_cast<int>(std::ceilf(*(std::max_element(box_y, box_y + 4)))),
            0, height - 1);
LDOUVLEV's avatar
LDOUVLEV committed
168
169
170
171
172

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

  cv::Point root_point[4];
LDOUBLEV's avatar
LDOUBLEV committed
173
174
175
176
177
178
179
180
  root_point[0] = cv::Point(static_cast<int>(array[0][0]) - xmin,
                            static_cast<int>(array[0][1]) - ymin);
  root_point[1] = cv::Point(static_cast<int>(array[1][0]) - xmin,
                            static_cast<int>(array[1][1]) - ymin);
  root_point[2] = cv::Point(static_cast<int>(array[2][0]) - xmin,
                            static_cast<int>(array[2][1]) - ymin);
  root_point[3] = cv::Point(static_cast<int>(array[3][0]) - xmin,
                            static_cast<int>(array[3][1]) - ymin);
LDOUBLEV's avatar
LDOUBLEV committed
181
  const cv::Point *ppt[1] = {root_point};
LDOUVLEV's avatar
LDOUVLEV committed
182
183
184
185
186
187
188
189
190
191
192
  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;
}

LDOUBLEV's avatar
LDOUBLEV committed
193
194
195
std::vector<std::vector<std::vector<int>>>
BoxesFromBitmap(const cv::Mat pred, const cv::Mat bitmap,
                std::map<std::string, double> Config) {
LDOUVLEV's avatar
LDOUVLEV committed
196
197
  const int min_size = 3;
  const int max_candidates = 1000;
LDOUBLEV's avatar
LDOUBLEV committed
198
199
  const float box_thresh = static_cast<float>(Config["det_db_box_thresh"]);
  const float unclip_ratio = static_cast<float>(Config["det_db_unclip_ratio"]);
LDOUVLEV's avatar
LDOUVLEV committed
200
201
202
203
204
205
206

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

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

LDOUBLEV's avatar
LDOUBLEV committed
207
208
  cv::findContours(bitmap, contours, hierarchy, cv::RETR_LIST,
                   cv::CHAIN_APPROX_SIMPLE);
LDOUVLEV's avatar
LDOUVLEV committed
209
210
211
212
213
214
215
216

  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++) {
    float ssid;
LDOUBLEV's avatar
LDOUBLEV committed
217
218
219
    if (contours[i].size() <= 2)
      continue;

LDOUVLEV's avatar
LDOUVLEV committed
220
221
222
223
224
225
226
227
228
229
230
231
232
    cv::RotatedRect box = cv::minAreaRect(contours[i]);
    auto array = GetMiniBoxes(box, ssid);

    auto box_for_unclip = array;
    // end get_mini_box

    if (ssid < min_size) {
      continue;
    }

    float score;
    score = BoxScoreFast(array, pred);
    // end box_score_fast
LDOUBLEV's avatar
LDOUBLEV committed
233
234
    if (score < box_thresh)
      continue;
LDOUVLEV's avatar
LDOUVLEV committed
235
236
237

    // start for unclip
    cv::RotatedRect points = Unclip(box_for_unclip, unclip_ratio);
LDOUBLEV's avatar
LDOUBLEV committed
238
239
    if (points.size.height < 1.001 && points.size.width < 1.001)
      continue;
LDOUVLEV's avatar
LDOUVLEV committed
240
241
242
243
244
    // end for unclip

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

LDOUBLEV's avatar
LDOUBLEV committed
245
246
    if (ssid < min_size + 2)
      continue;
LDOUVLEV's avatar
LDOUVLEV committed
247
248
249
250
251
252

    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++) {
LDOUBLEV's avatar
LDOUBLEV committed
253
254
255
256
257
258
259
      std::vector<int> a{
          static_cast<int>(clamp(
              roundf(cliparray[num_pt][0] / float(width) * float(dest_width)),
              float(0), float(dest_width))),
          static_cast<int>(clamp(
              roundf(cliparray[num_pt][1] / float(height) * float(dest_height)),
              float(0), float(dest_height)))};
LDOUVLEV's avatar
LDOUVLEV committed
260
261
262
263
      intcliparray.push_back(a);
    }
    boxes.push_back(intcliparray);

LDOUBLEV's avatar
LDOUBLEV committed
264
  } // end for
LDOUVLEV's avatar
LDOUVLEV committed
265
266
267
  return boxes;
}

LDOUBLEV's avatar
LDOUBLEV committed
268
269
270
std::vector<std::vector<std::vector<int>>>
FilterTagDetRes(std::vector<std::vector<std::vector<int>>> boxes, float ratio_h,
                float ratio_w, cv::Mat srcimg) {
LDOUVLEV's avatar
LDOUVLEV committed
271
272
273
274
  int oriimg_h = srcimg.rows;
  int oriimg_w = srcimg.cols;

  std::vector<std::vector<std::vector<int>>> root_points;
LDOUBLEV's avatar
LDOUBLEV committed
275
  for (int n = 0; n < static_cast<int>(boxes.size()); n++) {
LDOUVLEV's avatar
LDOUVLEV committed
276
    boxes[n] = OrderPointsClockwise(boxes[n]);
LDOUBLEV's avatar
LDOUBLEV committed
277
    for (int m = 0; m < static_cast<int>(boxes[0].size()); m++) {
LDOUVLEV's avatar
LDOUVLEV committed
278
279
280
      boxes[n][m][0] /= ratio_w;
      boxes[n][m][1] /= ratio_h;

LDOUBLEV's avatar
LDOUBLEV committed
281
282
283
284
      boxes[n][m][0] =
          static_cast<int>(std::min(std::max(boxes[n][m][0], 0), oriimg_w - 1));
      boxes[n][m][1] =
          static_cast<int>(std::min(std::max(boxes[n][m][1], 0), oriimg_h - 1));
LDOUVLEV's avatar
LDOUVLEV committed
285
286
287
288
289
    }
  }

  for (int n = 0; n < boxes.size(); n++) {
    int rect_width, rect_height;
LDOUBLEV's avatar
LDOUBLEV committed
290
291
292
293
294
295
    rect_width =
        static_cast<int>(sqrt(pow(boxes[n][0][0] - boxes[n][1][0], 2) +
                              pow(boxes[n][0][1] - boxes[n][1][1], 2)));
    rect_height =
        static_cast<int>(sqrt(pow(boxes[n][0][0] - boxes[n][3][0], 2) +
                              pow(boxes[n][0][1] - boxes[n][3][1], 2)));
LDOUBLEV's avatar
LDOUBLEV committed
296
297
    if (rect_width <= 10 || rect_height <= 10)
      continue;
LDOUVLEV's avatar
LDOUVLEV committed
298
299
300
    root_points.push_back(boxes[n]);
  }
  return root_points;
LDOUBLEV's avatar
update  
LDOUBLEV committed
301
}