VisionServer  v2.1.1-1-g21dc5465
FRC vision library
tfmodel.cpp
Go to the documentation of this file.
1#include "tfmodel.h"
2
3#ifndef EXCLUDE_TFLITE
4
5
6void loadObjectLabels(const std::string& f, std::vector<std::string>& objs) {
7 objs.clear();
8 std::ifstream file(f);
9 std::string line;
10 int32_t start, end;
11 std::getline(file, line, '\n');
12 if(line == "item {") {
13 while(std::getline(file, line, '\n')) {
14 start = end = -1;
15 for (size_t i = 0; i < line.size(); i++) {
16 if (line.at(i) == '"') {
17 if (start < 0) {
18 start = i + 1;
19 }
20 else {
21 end = i;
22 i = line.size(); // break
23 }
24 }
25 }
26 if (start >= 0 && end >= 0) {
27 objs.emplace_back(std::move(line.substr(start, end - start)));
28 }
29 }
30 } else {
31 objs.push_back(line);
32 while(std::getline(file, line, '\n')) {
33 objs.push_back(line);
34 }
35 }
36 file.close();
37}
38
39TfModel::TfModel(std::initializer_list<std::pair<const char*, Optimization> > models, size_t th) {
40
41 for(auto item = models.begin(); item != models.end(); item++) {
42 this->map = tflite::FlatBufferModel::BuildFromFile(item->first);
43 if(this->map) {
44 if(item->second == Optimization::EDGETPU && tpusAvailable()) { // switch-case if more optimization options
45 this->resolver.AddCustom(edgetpu::kCustomOp, edgetpu::RegisterCustomOp());
46 tflite::InterpreterBuilder builder(*this->map, this->resolver);
47 builder.SetNumThreads(th);
48 builder(&this->model);
49 this->edgetpu_context = edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice();
50 this->model->SetExternalContext(kTfLiteEdgeTpuContext, this->edgetpu_context.get());
51 } else {
52 tflite::InterpreterBuilder builder(*this->map, this->resolver);
53 builder.SetNumThreads(th);
54 builder(&this->model);
55 }
56 if(this->isValid()) {
57 break;
58 }
59 }
60 }
61
62 if(this->isValid()) {
63 this->model->AllocateTensors();
64 if(this->model->inputs().size() == 1) {
65 TfLiteTensor* input = this->model->input_tensor(0);
66 TfLiteIntArray* dims = input->dims;
67 this->input_size = cv::Size(dims->data[1], dims->data[2]);
68 if(dims->data[3] == 3 && input->type == kTfLiteUInt8) {
69 this->input_tensor = cv::Mat(this->input_size, CV_8UC3, input->data.data);
70 }
71 } else {
72 this->input_size = cv::Size(-1, -1);
73 }
74 }
75
76}
77
78#endif
TfModel()=delete
cv::Size input_size
Definition: tfmodel.h:55
std::unique_ptr< tflite::FlatBufferModel > map
Definition: tfmodel.h:49
bool isValid() const
Definition: tfmodel.h:44
std::unique_ptr< tflite::Interpreter > model
Definition: tfmodel.h:50
cv::Mat input_tensor
Definition: tfmodel.h:54
tflite::ops::builtin::BuiltinOpResolver resolver
Definition: tfmodel.h:52
std::shared_ptr< edgetpu::EdgeTpuContext > edgetpu_context
Definition: tfmodel.h:51
void loadObjectLabels(const std::string &f, std::vector< std::string > &objs)
Definition: tfmodel.cpp:6
size_t tpusAvailable()
Definition: tfmodel.h:23