1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #ifndef MEDIAPIPE_CALCULATORS_TFLITE_OBJECT_DETECTION_CALCULATOR_H_ #define MEDIAPIPE_CALCULATORS_TFLITE_OBJECT_DETECTION_CALCULATOR_H_
#include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h"
namespace mediapipe {
class ObjectDetectionCalculator : public CalculatorBase { public: static absl::Status GetContract(CalculatorContract* cc) { cc->Inputs().Tag("IMAGE").Set<ImageFrame>(); cc->Outputs().Tag("DETECTIONS").Set<std::vector<Detection>>(); cc->Options<ObjectDetectionOptions>(); return absl::OkStatus(); }
absl::Status Open(CalculatorContext* cc) override { const auto& options = cc->Options<ObjectDetectionOptions>(); model_ = LoadTFLiteModel(options.model_path()); interpreter_ = CreateInterpreter(model_); score_threshold_ = options.score_threshold(); max_detections_ = options.max_detections(); labels_ = LoadLabels(options.label_path()); return absl::OkStatus(); }
absl::Status Process(CalculatorContext* cc) override { const auto& image = cc->Inputs().Tag("IMAGE").Get<ImageFrame>(); cv::Mat input_mat = ImageFrameToMat(image); cv::Mat resized; cv::resize(input_mat, resized, cv::Size(320, 320)); resized.convertTo(resized, CV_32F, 1.0 / 127.5, -1.0); CopyToInputTensor(resized, interpreter_->input_tensor(0)); interpreter_->Invoke(); auto detections = ParseDetections( interpreter_->output_tensor(0), interpreter_->output_tensor(1), interpreter_->output_tensor(2), interpreter_->output_tensor(3)); detections.erase( std::remove_if(detections.begin(), detections.end(), [this](const Detection& d) { return d.score() < score_threshold_; }), detections.end()); detections = NonMaxSuppression(detections, 0.5); if (detections.size() > max_detections_) { detections.resize(max_detections_); } cc->Outputs().Tag("DETECTIONS").AddPacket( MakePacket<std::vector<Detection>>(detections).At(cc->InputTimestamp())); return absl::OkStatus(); }
private: std::unique_ptr<tflite::FlatBufferModel> model_; std::unique_ptr<tflite::Interpreter> interpreter_; float score_threshold_ = 0.5f; int max_detections_ = 10; std::vector<std::string> labels_; std::vector<Detection> ParseDetections( TfLiteTensor* boxes, TfLiteTensor* classes, TfLiteTensor* scores, TfLiteTensor* num_detections); std::vector<Detection> NonMaxSuppression( std::vector<Detection>& detections, float nms_threshold); };
REGISTER_CALCULATOR(ObjectDetectionCalculator);
}
#endif
|