yolo_box_op.h 7.3 KB
Newer Older
D
dengkaipeng 已提交
1
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
D
dengkaipeng 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15
   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. */

#pragma once
#include <algorithm>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
16 17
#include "paddle/phi/core/hostdevice.h"
#include "paddle/phi/kernels/funcs/math_function.h"
D
dengkaipeng 已提交
18 19 20 21 22 23 24

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename T>
D
dengkaipeng 已提交
25
HOSTDEVICE inline T sigmoid(T x) {
D
dengkaipeng 已提交
26 27 28 29
  return 1.0 / (1.0 + std::exp(-x));
}

template <typename T>
D
dengkaipeng 已提交
30
HOSTDEVICE inline void GetYoloBox(T* box, const T* x, const int* anchors, int i,
31 32 33
                                  int j, int an_idx, int grid_size_h,
                                  int grid_size_w, int input_size_h,
                                  int input_size_w, int index, int stride,
34 35
                                  int img_height, int img_width, float scale,
                                  float bias) {
36
  box[0] = (i + sigmoid<T>(x[index]) * scale + bias) * img_width / grid_size_w;
37
  box[1] = (j + sigmoid<T>(x[index + stride]) * scale + bias) * img_height /
38
           grid_size_h;
D
dengkaipeng 已提交
39
  box[2] = std::exp(x[index + 2 * stride]) * anchors[2 * an_idx] * img_width /
40
           input_size_w;
D
dengkaipeng 已提交
41
  box[3] = std::exp(x[index + 3 * stride]) * anchors[2 * an_idx + 1] *
42
           img_height / input_size_h;
D
dengkaipeng 已提交
43 44
}

D
dengkaipeng 已提交
45 46
HOSTDEVICE inline int GetEntryIndex(int batch, int an_idx, int hw_idx,
                                    int an_num, int an_stride, int stride,
47 48 49 50 51 52 53 54 55 56 57 58 59
                                    int entry, bool iou_aware) {
  if (iou_aware) {
    return (batch * an_num + an_idx) * an_stride +
           (batch * an_num + an_num + entry) * stride + hw_idx;
  } else {
    return (batch * an_num + an_idx) * an_stride + entry * stride + hw_idx;
  }
}

HOSTDEVICE inline int GetIoUIndex(int batch, int an_idx, int hw_idx, int an_num,
                                  int an_stride, int stride) {
  return batch * an_num * an_stride + (batch * an_num + an_idx) * stride +
         hw_idx;
D
dengkaipeng 已提交
60 61 62
}

template <typename T>
D
dengkaipeng 已提交
63
HOSTDEVICE inline void CalcDetectionBox(T* boxes, T* box, const int box_idx,
D
dengkaipeng 已提交
64
                                        const int img_height,
65
                                        const int img_width, bool clip_bbox) {
D
dengkaipeng 已提交
66 67 68 69
  boxes[box_idx] = box[0] - box[2] / 2;
  boxes[box_idx + 1] = box[1] - box[3] / 2;
  boxes[box_idx + 2] = box[0] + box[2] / 2;
  boxes[box_idx + 3] = box[1] + box[3] / 2;
D
dengkaipeng 已提交
70

71 72 73 74 75 76 77 78 79 80 81
  if (clip_bbox) {
    boxes[box_idx] = boxes[box_idx] > 0 ? boxes[box_idx] : static_cast<T>(0);
    boxes[box_idx + 1] =
        boxes[box_idx + 1] > 0 ? boxes[box_idx + 1] : static_cast<T>(0);
    boxes[box_idx + 2] = boxes[box_idx + 2] < img_width - 1
                             ? boxes[box_idx + 2]
                             : static_cast<T>(img_width - 1);
    boxes[box_idx + 3] = boxes[box_idx + 3] < img_height - 1
                             ? boxes[box_idx + 3]
                             : static_cast<T>(img_height - 1);
  }
D
dengkaipeng 已提交
82 83 84
}

template <typename T>
D
dengkaipeng 已提交
85 86 87 88
HOSTDEVICE inline void CalcLabelScore(T* scores, const T* input,
                                      const int label_idx, const int score_idx,
                                      const int class_num, const T conf,
                                      const int stride) {
D
dengkaipeng 已提交
89 90 91 92 93 94 95 96 97 98
  for (int i = 0; i < class_num; i++) {
    scores[score_idx + i] = conf * sigmoid<T>(input[label_idx + i * stride]);
  }
}

template <typename T>
class YoloBoxKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* input = ctx.Input<Tensor>("X");
99
    auto* imgsize = ctx.Input<Tensor>("ImgSize");
D
dengkaipeng 已提交
100 101 102 103 104 105
    auto* boxes = ctx.Output<Tensor>("Boxes");
    auto* scores = ctx.Output<Tensor>("Scores");
    auto anchors = ctx.Attr<std::vector<int>>("anchors");
    int class_num = ctx.Attr<int>("class_num");
    float conf_thresh = ctx.Attr<float>("conf_thresh");
    int downsample_ratio = ctx.Attr<int>("downsample_ratio");
106
    bool clip_bbox = ctx.Attr<bool>("clip_bbox");
107 108
    bool iou_aware = ctx.Attr<bool>("iou_aware");
    float iou_aware_factor = ctx.Attr<float>("iou_aware_factor");
109 110
    float scale = ctx.Attr<float>("scale_x_y");
    float bias = -0.5 * (scale - 1.);
D
dengkaipeng 已提交
111 112 113 114 115 116

    const int n = input->dims()[0];
    const int h = input->dims()[2];
    const int w = input->dims()[3];
    const int box_num = boxes->dims()[1];
    const int an_num = anchors.size() / 2;
117 118
    int input_size_h = downsample_ratio * h;
    int input_size_w = downsample_ratio * w;
D
dengkaipeng 已提交
119 120 121 122

    const int stride = h * w;
    const int an_stride = (class_num + 5) * stride;

D
dengkaipeng 已提交
123 124 125 126
    Tensor anchors_;
    auto anchors_data =
        anchors_.mutable_data<int>({an_num * 2}, ctx.GetPlace());
    std::copy(anchors.begin(), anchors.end(), anchors_data);
D
dengkaipeng 已提交
127

D
dengkaipeng 已提交
128
    const T* input_data = input->data<T>();
129
    const int* imgsize_data = imgsize->data<int>();
D
dengkaipeng 已提交
130 131 132 133 134 135
    T* boxes_data = boxes->mutable_data<T>({n, box_num, 4}, ctx.GetPlace());
    memset(boxes_data, 0, boxes->numel() * sizeof(T));
    T* scores_data =
        scores->mutable_data<T>({n, box_num, class_num}, ctx.GetPlace());
    memset(scores_data, 0, scores->numel() * sizeof(T));

D
dengkaipeng 已提交
136
    T box[4];
D
dengkaipeng 已提交
137
    for (int i = 0; i < n; i++) {
138 139 140
      int img_height = imgsize_data[2 * i];
      int img_width = imgsize_data[2 * i + 1];

D
dengkaipeng 已提交
141 142 143
      for (int j = 0; j < an_num; j++) {
        for (int k = 0; k < h; k++) {
          for (int l = 0; l < w; l++) {
144 145
            int obj_idx = GetEntryIndex(i, j, k * w + l, an_num, an_stride,
                                        stride, 4, iou_aware);
D
dengkaipeng 已提交
146
            T conf = sigmoid<T>(input_data[obj_idx]);
147 148 149 150 151 152 153
            if (iou_aware) {
              int iou_idx =
                  GetIoUIndex(i, j, k * w + l, an_num, an_stride, stride);
              T iou = sigmoid<T>(input_data[iou_idx]);
              conf = pow(conf, static_cast<T>(1. - iou_aware_factor)) *
                     pow(iou, static_cast<T>(iou_aware_factor));
            }
D
dengkaipeng 已提交
154 155 156 157
            if (conf < conf_thresh) {
              continue;
            }

158 159
            int box_idx = GetEntryIndex(i, j, k * w + l, an_num, an_stride,
                                        stride, 0, iou_aware);
160 161 162
            GetYoloBox<T>(box, input_data, anchors_data, l, k, j, h, w,
                          input_size_h, input_size_w, box_idx, stride,
                          img_height, img_width, scale, bias);
D
dengkaipeng 已提交
163
            box_idx = (i * box_num + j * stride + k * w + l) * 4;
164 165
            CalcDetectionBox<T>(boxes_data, box, box_idx, img_height, img_width,
                                clip_bbox);
D
dengkaipeng 已提交
166

167 168
            int label_idx = GetEntryIndex(i, j, k * w + l, an_num, an_stride,
                                          stride, 5, iou_aware);
D
dengkaipeng 已提交
169 170 171 172 173 174 175 176 177 178 179 180
            int score_idx = (i * box_num + j * stride + k * w + l) * class_num;
            CalcLabelScore<T>(scores_data, input_data, label_idx, score_idx,
                              class_num, conf, stride);
          }
        }
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle