Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 1 | #include "yolov5.h" |
| 2 | |
Adam Snaider | 13d48d9 | 2023-08-03 12:20:15 -0700 | [diff] [blame] | 3 | #pragma clang diagnostic ignored "-Wunused-parameter" |
| 4 | |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 5 | #include <tensorflow/lite/c/common.h> |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 6 | #include <tensorflow/lite/interpreter.h> |
| 7 | #include <tensorflow/lite/kernels/register.h> |
| 8 | #include <tensorflow/lite/model.h> |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 9 | #include <tflite/public/edgetpu.h> |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 10 | #include <tflite/public/edgetpu_c.h> |
| 11 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 12 | #include <chrono> |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 13 | #include <string> |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 14 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 15 | #include "absl/types/span.h" |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 16 | #include "gflags/gflags.h" |
| 17 | #include "glog/logging.h" |
Philipp Schrader | 790cb54 | 2023-07-05 21:06:52 -0700 | [diff] [blame] | 18 | #include <opencv2/dnn.hpp> |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 19 | |
| 20 | DEFINE_double(conf_threshold, 0.9, |
| 21 | "Threshold value for confidence scores. Detections with a " |
| 22 | "confidence score below this value will be ignored."); |
| 23 | |
| 24 | DEFINE_double( |
| 25 | nms_threshold, 0.5, |
| 26 | "Threshold value for non-maximum suppression. Detections with an " |
| 27 | "intersection-over-union value below this value will be removed."); |
| 28 | |
| 29 | DEFINE_int32(nthreads, 6, "Number of threads to use during inference."); |
| 30 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 31 | DEFINE_bool(visualize_detections, false, "Display inference output"); |
| 32 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 33 | namespace y2023 { |
| 34 | namespace vision { |
| 35 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 36 | class YOLOV5Impl : public YOLOV5 { |
| 37 | public: |
| 38 | // Takes a model path as string and and loads a pre-trained |
| 39 | // YOLOv5 model from the specified path. |
| 40 | void LoadModel(const std::string path); |
| 41 | |
| 42 | // Takes an image and returns a Detection. |
| 43 | std::vector<Detection> ProcessImage(cv::Mat image); |
| 44 | |
| 45 | private: |
| 46 | // Convert an OpenCV Mat object to a tensor input |
| 47 | // that can be fed to the TensorFlow Lite model. |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 48 | void ConvertCVMatToTensor(cv::Mat src, absl::Span<uint8_t> tensor); |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 49 | |
| 50 | // Resizes, converts color space, and converts |
| 51 | // image data type before inference. |
| 52 | void Preprocess(cv::Mat image); |
| 53 | |
| 54 | // Converts a TensorFlow Lite tensor to a 2D vector. |
| 55 | std::vector<std::vector<float>> TensorToVector2D(TfLiteTensor *src_tensor, |
| 56 | const int rows, |
| 57 | const int columns); |
| 58 | |
| 59 | // Performs non-maximum suppression to remove overlapping bounding boxes. |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 60 | std::vector<Detection> NonMaximumSupression( |
| 61 | const std::vector<std::vector<float>> &orig_preds, const int rows, |
| 62 | const int columns, std::vector<Detection> *detections, |
| 63 | std::vector<int> *indices); |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 64 | // Models |
| 65 | std::unique_ptr<tflite::FlatBufferModel> model_; |
| 66 | std::unique_ptr<tflite::Interpreter> interpreter_; |
| 67 | tflite::StderrReporter error_reporter_; |
| 68 | |
| 69 | // Parameters of interpreter's input |
| 70 | int input_; |
| 71 | int in_height_; |
| 72 | int in_width_; |
| 73 | int in_channels_; |
| 74 | int in_type_; |
| 75 | |
| 76 | // Parameters of original image |
| 77 | int img_height_; |
| 78 | int img_width_; |
| 79 | |
| 80 | // Input of the interpreter |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 81 | absl::Span<uint8_t> input_8_; |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 82 | |
| 83 | // Subtract this offset from class labels to get the actual label. |
| 84 | static constexpr int kClassIdOffset = 5; |
| 85 | }; |
| 86 | |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 87 | std::unique_ptr<YOLOV5> MakeYOLOV5() { return std::make_unique<YOLOV5Impl>(); } |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 88 | |
| 89 | void YOLOV5Impl::LoadModel(const std::string path) { |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 90 | VLOG(1) << "Load model: Start"; |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 91 | |
| 92 | tflite::ops::builtin::BuiltinOpResolver resolver; |
| 93 | |
| 94 | model_ = tflite::FlatBufferModel::VerifyAndBuildFromFile(path.c_str()); |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 95 | CHECK(model_); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 96 | CHECK(model_->initialized()); |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 97 | VLOG(1) << "Load model: Build model from file success"; |
| 98 | |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 99 | CHECK_EQ(tflite::InterpreterBuilder(*model_, resolver)(&interpreter_), |
| 100 | kTfLiteOk); |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 101 | VLOG(1) << "Load model: Interpreter builder success"; |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 102 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 103 | size_t num_devices; |
| 104 | std::unique_ptr<edgetpu_device, decltype(&edgetpu_free_devices)> devices( |
| 105 | edgetpu_list_devices(&num_devices), &edgetpu_free_devices); |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 106 | |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 107 | CHECK_EQ(num_devices, 1ul); |
| 108 | const auto &device = devices.get()[0]; |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 109 | VLOG(1) << "Load model: Got Devices"; |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 110 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 111 | auto *delegate = |
| 112 | edgetpu_create_delegate(device.type, device.path, nullptr, 0); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 113 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 114 | interpreter_->ModifyGraphWithDelegate(delegate); |
| 115 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 116 | VLOG(1) << "Load model: Modify graph with delegate complete"; |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 117 | |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 118 | TfLiteStatus status = interpreter_->AllocateTensors(); |
| 119 | CHECK_EQ(status, kTfLiteOk); |
| 120 | CHECK(interpreter_); |
| 121 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 122 | VLOG(1) << "Load model: Allocate tensors success"; |
| 123 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 124 | input_ = interpreter_->inputs()[0]; |
| 125 | TfLiteIntArray *dims = interpreter_->tensor(input_)->dims; |
| 126 | in_height_ = dims->data[1]; |
| 127 | in_width_ = dims->data[2]; |
| 128 | in_channels_ = dims->data[3]; |
| 129 | in_type_ = interpreter_->tensor(input_)->type; |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 130 | |
| 131 | int tensor_size = 1; |
| 132 | for (int i = 0; i < dims->size; i++) { |
| 133 | tensor_size *= dims->data[i]; |
| 134 | } |
| 135 | input_8_ = |
| 136 | absl::Span(interpreter_->typed_tensor<uint8_t>(input_), tensor_size); |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 137 | |
| 138 | interpreter_->SetNumThreads(FLAGS_nthreads); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 139 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 140 | VLOG(1) << "Load model: Done"; |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 141 | } |
| 142 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 143 | void YOLOV5Impl::ConvertCVMatToTensor(cv::Mat src, absl::Span<uint8_t> tensor) { |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 144 | CHECK(src.type() == CV_8UC3); |
| 145 | int n = 0, nc = src.channels(), ne = src.elemSize(); |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 146 | VLOG(2) << "ConvertCVMatToTensor: Rows " << src.rows; |
| 147 | VLOG(2) << "ConvertCVMatToTensor: Cols " << src.cols; |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 148 | for (int y = 0; y < src.rows; ++y) { |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 149 | auto *row_ptr = src.ptr<uint8_t>(y); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 150 | for (int x = 0; x < src.cols; ++x) { |
| 151 | for (int c = 0; c < nc; ++c) { |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 152 | tensor[n++] = *(row_ptr + x * ne + c); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 153 | } |
| 154 | } |
| 155 | } |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 156 | } |
| 157 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 158 | std::vector<std::vector<float>> YOLOV5Impl::TensorToVector2D( |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 159 | TfLiteTensor *src_tensor, const int rows, const int columns) { |
| 160 | auto scale = src_tensor->params.scale; |
| 161 | auto zero_point = src_tensor->params.zero_point; |
| 162 | std::vector<std::vector<float>> result_vec; |
| 163 | for (int32_t i = 0; i < rows; i++) { |
| 164 | std::vector<float> row_values; |
| 165 | for (int32_t j = 0; j < columns; j++) { |
| 166 | float val_float = |
| 167 | ((static_cast<int32_t>(src_tensor->data.uint8[i * columns + j])) - |
| 168 | zero_point) * |
| 169 | scale; |
| 170 | row_values.push_back(val_float); |
| 171 | } |
| 172 | result_vec.push_back(row_values); |
| 173 | } |
| 174 | return result_vec; |
| 175 | } |
| 176 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 177 | std::vector<Detection> YOLOV5Impl::NonMaximumSupression( |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 178 | const std::vector<std::vector<float>> &orig_preds, const int rows, |
| 179 | const int columns, std::vector<Detection> *detections, |
| 180 | std::vector<int> *indices) |
| 181 | |
| 182 | { |
| 183 | std::vector<float> scores; |
| 184 | double confidence; |
| 185 | cv::Point class_id; |
| 186 | |
| 187 | for (int i = 0; i < rows; i++) { |
| 188 | if (orig_preds[i][4] > FLAGS_conf_threshold) { |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 189 | float x = orig_preds[i][0]; |
| 190 | float y = orig_preds[i][1]; |
| 191 | float w = orig_preds[i][2]; |
| 192 | float h = orig_preds[i][3]; |
| 193 | int left = static_cast<int>((x - 0.5 * w) * img_width_); |
| 194 | int top = static_cast<int>((y - 0.5 * h) * img_height_); |
| 195 | int width = static_cast<int>(w * img_width_); |
| 196 | int height = static_cast<int>(h * img_height_); |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 197 | |
| 198 | for (int j = 5; j < columns; j++) { |
| 199 | scores.push_back(orig_preds[i][j] * orig_preds[i][4]); |
| 200 | } |
| 201 | |
| 202 | cv::minMaxLoc(scores, nullptr, &confidence, nullptr, &class_id); |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 203 | scores.clear(); |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 204 | if (confidence > FLAGS_conf_threshold) { |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 205 | Detection detection{cv::Rect(left, top, width, height), confidence, |
| 206 | class_id.x}; |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 207 | detections->push_back(detection); |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | std::vector<cv::Rect> boxes; |
| 213 | std::vector<float> confidences; |
| 214 | |
| 215 | for (const Detection &d : *detections) { |
| 216 | boxes.push_back(d.box); |
| 217 | confidences.push_back(d.confidence); |
| 218 | } |
| 219 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 220 | cv::dnn::NMSBoxes(boxes, confidences, FLAGS_conf_threshold, |
| 221 | FLAGS_nms_threshold, *indices); |
| 222 | |
| 223 | std::vector<Detection> filtered_detections; |
| 224 | for (size_t i = 0; i < indices->size(); i++) { |
| 225 | filtered_detections.push_back((*detections)[(*indices)[i]]); |
| 226 | } |
| 227 | |
| 228 | VLOG(1) << "NonMaximumSupression: " << detections->size() - indices->size() |
| 229 | << " detections filtered out"; |
| 230 | |
| 231 | return filtered_detections; |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 232 | } |
| 233 | |
Filip Kujawa | 26a2366 | 2023-04-08 16:19:13 -0700 | [diff] [blame] | 234 | std::vector<Detection> YOLOV5Impl::ProcessImage(cv::Mat frame) { |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 235 | VLOG(1) << "\n"; |
| 236 | |
| 237 | auto start = std::chrono::high_resolution_clock::now(); |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 238 | img_height_ = frame.rows; |
| 239 | img_width_ = frame.cols; |
| 240 | |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 241 | cv::resize(frame, frame, cv::Size(in_height_, in_width_), cv::INTER_CUBIC); |
| 242 | cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB); |
| 243 | frame.convertTo(frame, CV_8U); |
| 244 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 245 | ConvertCVMatToTensor(frame, input_8_); |
| 246 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 247 | TfLiteStatus status = interpreter_->Invoke(); |
| 248 | CHECK_EQ(status, kTfLiteOk); |
| 249 | |
| 250 | int output_tensor_index = interpreter_->outputs()[0]; |
| 251 | TfLiteIntArray *out_dims = interpreter_->tensor(output_tensor_index)->dims; |
| 252 | int num_rows = out_dims->data[1]; |
| 253 | int num_columns = out_dims->data[2]; |
| 254 | |
| 255 | TfLiteTensor *src_tensor = interpreter_->tensor(interpreter_->outputs()[0]); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 256 | |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 257 | std::vector<std::vector<float>> orig_preds = |
| 258 | TensorToVector2D(src_tensor, num_rows, num_columns); |
| 259 | |
| 260 | std::vector<int> indices; |
| 261 | std::vector<Detection> detections; |
| 262 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 263 | std::vector<Detection> filtered_detections; |
| 264 | filtered_detections = NonMaximumSupression(orig_preds, num_rows, num_columns, |
| 265 | &detections, &indices); |
| 266 | VLOG(1) << "---"; |
| 267 | for (size_t i = 0; i < filtered_detections.size(); i++) { |
| 268 | VLOG(1) << "Detection #" << i << " | Class ID #" |
| 269 | << filtered_detections[i].class_id << " @ " |
| 270 | << filtered_detections[i].confidence << " confidence"; |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 271 | } |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 272 | |
| 273 | VLOG(1) << "---"; |
| 274 | |
| 275 | auto stop = std::chrono::high_resolution_clock::now(); |
| 276 | |
| 277 | VLOG(1) << "Inference time: " |
| 278 | << std::chrono::duration_cast<std::chrono::milliseconds>(stop - start) |
| 279 | .count(); |
| 280 | |
| 281 | if (FLAGS_visualize_detections) { |
| 282 | cv::resize(frame, frame, cv::Size(img_width_, img_height_), 0, 0, true); |
| 283 | for (size_t i = 0; i < filtered_detections.size(); i++) { |
| 284 | VLOG(1) << "Bounding Box | X: " << filtered_detections[i].box.x |
| 285 | << " Y: " << filtered_detections[i].box.y |
| 286 | << " W: " << filtered_detections[i].box.width |
| 287 | << " H: " << filtered_detections[i].box.height; |
| 288 | cv::rectangle(frame, filtered_detections[i].box, cv::Scalar(255, 0, 0), |
| 289 | 2); |
Filip Kujawa | 64f7cf9 | 2023-04-14 14:35:42 -0700 | [diff] [blame] | 290 | |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 291 | cv::putText( |
Filip Kujawa | 64f7cf9 | 2023-04-14 14:35:42 -0700 | [diff] [blame] | 292 | frame, |
| 293 | "#" + std::to_string(filtered_detections[i].class_id) + " at " + |
| 294 | std::to_string(filtered_detections[i].confidence) + " confidence", |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 295 | cv::Point(filtered_detections[i].box.x, filtered_detections[i].box.y), |
Filip Kujawa | 64f7cf9 | 2023-04-14 14:35:42 -0700 | [diff] [blame] | 296 | cv::FONT_HERSHEY_COMPLEX, 1.0, cv::Scalar(0, 0, 255), 2, cv::LINE_AA); |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 297 | } |
| 298 | cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB); |
| 299 | cv::imshow("yolo", frame); |
| 300 | cv::waitKey(10); |
Filip Kujawa | 8c76e5d | 2023-04-08 16:20:27 -0700 | [diff] [blame] | 301 | } |
Filip Kujawa | f3b8adb | 2023-04-07 21:00:49 -0700 | [diff] [blame] | 302 | |
| 303 | return filtered_detections; |
Filip Kujawa | dc7d47c | 2023-04-08 16:16:51 -0700 | [diff] [blame] | 304 | }; |
| 305 | |
| 306 | } // namespace vision |
| 307 | } // namespace y2023 |