Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 1 | #include "yolov5.h" |
| 2 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 3 | #include <tensorflow/lite/interpreter.h> |
| 4 | #include <tensorflow/lite/kernels/register.h> |
| 5 | #include <tensorflow/lite/model.h> |
| 6 | #include <tflite/public/edgetpu_c.h> |
| 7 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 8 | #include <opencv2/core.hpp> |
| 9 | |
| 10 | #include "gflags/gflags.h" |
| 11 | #include "glog/logging.h" |
| 12 | |
| 13 | DEFINE_double(conf_threshold, 0.9, |
| 14 | "Threshold value for confidence scores. Detections with a " |
| 15 | "confidence score below this value will be ignored."); |
| 16 | |
| 17 | DEFINE_double( |
| 18 | nms_threshold, 0.5, |
| 19 | "Threshold value for non-maximum suppression. Detections with an " |
| 20 | "intersection-over-union value below this value will be removed."); |
| 21 | |
| 22 | DEFINE_int32(nthreads, 6, "Number of threads to use during inference."); |
| 23 | |
| 24 | namespace y2023 { |
| 25 | namespace vision { |
| 26 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 27 | class YOLOV5Impl : public YOLOV5 { |
| 28 | public: |
| 29 | // Takes a model path as string and and loads a pre-trained |
| 30 | // YOLOv5 model from the specified path. |
| 31 | void LoadModel(const std::string path); |
| 32 | |
| 33 | // Takes an image and returns a Detection. |
| 34 | std::vector<Detection> ProcessImage(cv::Mat image); |
| 35 | |
| 36 | private: |
| 37 | // Convert an OpenCV Mat object to a tensor input |
| 38 | // that can be fed to the TensorFlow Lite model. |
| 39 | void ConvertCVMatToTensor(const cv::Mat &src, uint8_t *in); |
| 40 | |
| 41 | // Resizes, converts color space, and converts |
| 42 | // image data type before inference. |
| 43 | void Preprocess(cv::Mat image); |
| 44 | |
| 45 | // Converts a TensorFlow Lite tensor to a 2D vector. |
| 46 | std::vector<std::vector<float>> TensorToVector2D(TfLiteTensor *src_tensor, |
| 47 | const int rows, |
| 48 | const int columns); |
| 49 | |
| 50 | // Performs non-maximum suppression to remove overlapping bounding boxes. |
| 51 | void NonMaximumSupression(const std::vector<std::vector<float>> &orig_preds, |
| 52 | const int rows, const int columns, |
| 53 | std::vector<Detection> *detections, |
| 54 | std::vector<int> *indices); |
| 55 | // Models |
| 56 | std::unique_ptr<tflite::FlatBufferModel> model_; |
| 57 | std::unique_ptr<tflite::Interpreter> interpreter_; |
| 58 | tflite::StderrReporter error_reporter_; |
| 59 | |
| 60 | // Parameters of interpreter's input |
| 61 | int input_; |
| 62 | int in_height_; |
| 63 | int in_width_; |
| 64 | int in_channels_; |
| 65 | int in_type_; |
| 66 | |
| 67 | // Parameters of original image |
| 68 | int img_height_; |
| 69 | int img_width_; |
| 70 | |
| 71 | // Input of the interpreter |
| 72 | uint8_t *input_8_; |
| 73 | |
| 74 | // Subtract this offset from class labels to get the actual label. |
| 75 | static constexpr int kClassIdOffset = 5; |
| 76 | }; |
| 77 | |
| 78 | std::unique_ptr<YOLOV5> MakeYOLOV5() { |
| 79 | YOLOV5Impl *yolo = new YOLOV5Impl(); |
| 80 | return std::unique_ptr<YOLOV5>(yolo); |
| 81 | } |
| 82 | |
| 83 | void YOLOV5Impl::LoadModel(const std::string path) { |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 84 | model_ = tflite::FlatBufferModel::BuildFromFile(path.c_str()); |
| 85 | CHECK(model_); |
| 86 | size_t num_devices; |
| 87 | std::unique_ptr<edgetpu_device, decltype(&edgetpu_free_devices)> devices( |
| 88 | edgetpu_list_devices(&num_devices), &edgetpu_free_devices); |
| 89 | const auto &device = devices.get()[0]; |
| 90 | CHECK_EQ(num_devices, 1ul); |
| 91 | tflite::ops::builtin::BuiltinOpResolver resolver; |
| 92 | CHECK_EQ(tflite::InterpreterBuilder(*model_, resolver)(&interpreter_), |
| 93 | kTfLiteOk); |
| 94 | |
| 95 | auto *delegate = |
| 96 | edgetpu_create_delegate(device.type, device.path, nullptr, 0); |
| 97 | interpreter_->ModifyGraphWithDelegate(delegate); |
| 98 | |
| 99 | TfLiteStatus status = interpreter_->AllocateTensors(); |
| 100 | CHECK(status == kTfLiteOk); |
| 101 | |
| 102 | input_ = interpreter_->inputs()[0]; |
| 103 | TfLiteIntArray *dims = interpreter_->tensor(input_)->dims; |
| 104 | in_height_ = dims->data[1]; |
| 105 | in_width_ = dims->data[2]; |
| 106 | in_channels_ = dims->data[3]; |
| 107 | in_type_ = interpreter_->tensor(input_)->type; |
| 108 | input_8_ = interpreter_->typed_tensor<uint8_t>(input_); |
| 109 | |
| 110 | interpreter_->SetNumThreads(FLAGS_nthreads); |
| 111 | } |
| 112 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 113 | void YOLOV5Impl::Preprocess(cv::Mat image) { |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 114 | cv::resize(image, image, cv::Size(in_height_, in_width_), cv::INTER_CUBIC); |
| 115 | cv::cvtColor(image, image, cv::COLOR_BGR2RGB); |
| 116 | image.convertTo(image, CV_8U); |
| 117 | } |
| 118 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 119 | void YOLOV5Impl::ConvertCVMatToTensor(const cv::Mat &src, uint8_t *in) { |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 120 | CHECK(src.type() == CV_8UC3); |
| 121 | int n = 0, nc = src.channels(), ne = src.elemSize(); |
| 122 | for (int y = 0; y < src.rows; ++y) |
| 123 | for (int x = 0; x < src.cols; ++x) |
| 124 | for (int c = 0; c < nc; ++c) |
| 125 | in[n++] = src.data[y * src.step + x * ne + c]; |
| 126 | } |
| 127 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 128 | std::vector<std::vector<float>> YOLOV5Impl::TensorToVector2D( |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 129 | TfLiteTensor *src_tensor, const int rows, const int columns) { |
| 130 | auto scale = src_tensor->params.scale; |
| 131 | auto zero_point = src_tensor->params.zero_point; |
| 132 | std::vector<std::vector<float>> result_vec; |
| 133 | for (int32_t i = 0; i < rows; i++) { |
| 134 | std::vector<float> row_values; |
| 135 | for (int32_t j = 0; j < columns; j++) { |
| 136 | float val_float = |
| 137 | ((static_cast<int32_t>(src_tensor->data.uint8[i * columns + j])) - |
| 138 | zero_point) * |
| 139 | scale; |
| 140 | row_values.push_back(val_float); |
| 141 | } |
| 142 | result_vec.push_back(row_values); |
| 143 | } |
| 144 | return result_vec; |
| 145 | } |
| 146 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 147 | void YOLOV5Impl::NonMaximumSupression( |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 148 | const std::vector<std::vector<float>> &orig_preds, const int rows, |
| 149 | const int columns, std::vector<Detection> *detections, |
| 150 | std::vector<int> *indices) |
| 151 | |
| 152 | { |
| 153 | std::vector<float> scores; |
| 154 | double confidence; |
| 155 | cv::Point class_id; |
| 156 | |
| 157 | for (int i = 0; i < rows; i++) { |
| 158 | if (orig_preds[i][4] > FLAGS_conf_threshold) { |
| 159 | int left = (orig_preds[i][0] - orig_preds[i][2] / 2) * img_width_; |
| 160 | int top = (orig_preds[i][1] - orig_preds[i][3] / 2) * img_height_; |
| 161 | int w = orig_preds[i][2] * img_width_; |
| 162 | int h = orig_preds[i][3] * img_height_; |
| 163 | |
| 164 | for (int j = 5; j < columns; j++) { |
| 165 | scores.push_back(orig_preds[i][j] * orig_preds[i][4]); |
| 166 | } |
| 167 | |
| 168 | cv::minMaxLoc(scores, nullptr, &confidence, nullptr, &class_id); |
| 169 | if (confidence > FLAGS_conf_threshold) { |
| 170 | Detection detection{cv::Rect(left, top, w, h), confidence, |
| 171 | class_id.x - kClassIdOffset}; |
| 172 | detections->push_back(detection); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | std::vector<cv::Rect> boxes; |
| 178 | std::vector<float> confidences; |
| 179 | |
| 180 | for (const Detection &d : *detections) { |
| 181 | boxes.push_back(d.box); |
| 182 | confidences.push_back(d.confidence); |
| 183 | } |
| 184 | |
| 185 | cv::dnn::NMSBoxes(boxes, confidences, FLAGS_conf_threshold, |
| 186 | FLAGS_nms_threshold, *indices); |
| 187 | } |
| 188 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame^] | 189 | std::vector<Detection> YOLOV5Impl::ProcessImage(cv::Mat frame) { |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 190 | img_height_ = frame.rows; |
| 191 | img_width_ = frame.cols; |
| 192 | |
| 193 | Preprocess(frame); |
| 194 | ConvertCVMatToTensor(frame, input_8_); |
| 195 | |
| 196 | // Inference |
| 197 | TfLiteStatus status = interpreter_->Invoke(); |
| 198 | CHECK_EQ(status, kTfLiteOk); |
| 199 | |
| 200 | int output_tensor_index = interpreter_->outputs()[0]; |
| 201 | TfLiteIntArray *out_dims = interpreter_->tensor(output_tensor_index)->dims; |
| 202 | int num_rows = out_dims->data[1]; |
| 203 | int num_columns = out_dims->data[2]; |
| 204 | |
| 205 | TfLiteTensor *src_tensor = interpreter_->tensor(interpreter_->outputs()[0]); |
| 206 | std::vector<std::vector<float>> orig_preds = |
| 207 | TensorToVector2D(src_tensor, num_rows, num_columns); |
| 208 | |
| 209 | std::vector<int> indices; |
| 210 | std::vector<Detection> detections; |
| 211 | |
| 212 | NonMaximumSupression(orig_preds, num_rows, num_columns, &detections, |
| 213 | &indices); |
| 214 | |
| 215 | return detections; |
| 216 | }; |
| 217 | |
| 218 | } // namespace vision |
| 219 | } // namespace y2023 |