CTfLiteClass.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #include "CTfLiteClass.h"
  2. #include "ClassLogFile.h"
  3. #include "Helper.h"
  4. #include "psram.h"
  5. #include "esp_log.h"
  6. #include "../../include/defines.h"
  7. #include <sys/stat.h>
  8. // #define DEBUG_DETAIL_ON
  9. static const char *TAG = "TFLITE";
  10. void CTfLiteClass::MakeStaticResolver()
  11. {
  12. resolver.AddFullyConnected();
  13. resolver.AddReshape();
  14. resolver.AddSoftmax();
  15. resolver.AddConv2D();
  16. resolver.AddMaxPool2D();
  17. resolver.AddQuantize();
  18. resolver.AddMul();
  19. resolver.AddAdd();
  20. resolver.AddLeakyRelu();
  21. resolver.AddDequantize();
  22. }
  23. float CTfLiteClass::GetOutputValue(int nr)
  24. {
  25. TfLiteTensor* output2 = this->interpreter->output(0);
  26. int numeroutput = output2->dims->data[1];
  27. if ((nr+1) > numeroutput)
  28. return -1000;
  29. return output2->data.f[nr];
  30. }
  31. int CTfLiteClass::GetClassFromImageBasis(CImageBasis *rs)
  32. {
  33. if (!LoadInputImageBasis(rs))
  34. return -1000;
  35. Invoke();
  36. return GetOutClassification();
  37. }
  38. int CTfLiteClass::GetOutClassification(int _von, int _bis)
  39. {
  40. TfLiteTensor* output2 = interpreter->output(0);
  41. float zw_max;
  42. float zw;
  43. int zw_class;
  44. if (output2 == NULL)
  45. return -1;
  46. int numeroutput = output2->dims->data[1];
  47. //ESP_LOGD(TAG, "number output neurons: %d", numeroutput);
  48. if (_bis == -1)
  49. _bis = numeroutput -1;
  50. if (_von == -1)
  51. _von = 0;
  52. if (_bis >= numeroutput)
  53. {
  54. ESP_LOGD(TAG, "NUMBER OF OUTPUT NEURONS does not match required classification!");
  55. return -1;
  56. }
  57. zw_max = output2->data.f[_von];
  58. zw_class = _von;
  59. for (int i = _von + 1; i <= _bis; ++i)
  60. {
  61. zw = output2->data.f[i];
  62. if (zw > zw_max)
  63. {
  64. zw_max = zw;
  65. zw_class = i;
  66. }
  67. }
  68. return (zw_class - _von);
  69. }
  70. void CTfLiteClass::GetInputDimension(bool silent = false)
  71. {
  72. TfLiteTensor* input2 = this->interpreter->input(0);
  73. int numdim = input2->dims->size;
  74. if (!silent) ESP_LOGD(TAG, "NumDimension: %d", numdim);
  75. int sizeofdim;
  76. for (int j = 0; j < numdim; ++j)
  77. {
  78. sizeofdim = input2->dims->data[j];
  79. if (!silent) ESP_LOGD(TAG, "SizeOfDimension %d: %d", j, sizeofdim);
  80. if (j == 1) im_height = sizeofdim;
  81. if (j == 2) im_width = sizeofdim;
  82. if (j == 3) im_channel = sizeofdim;
  83. }
  84. }
  85. int CTfLiteClass::ReadInputDimenstion(int _dim)
  86. {
  87. if (_dim == 0)
  88. return im_width;
  89. if (_dim == 1)
  90. return im_height;
  91. if (_dim == 2)
  92. return im_channel;
  93. return -1;
  94. }
  95. int CTfLiteClass::GetAnzOutPut(bool silent)
  96. {
  97. TfLiteTensor* output2 = this->interpreter->output(0);
  98. int numdim = output2->dims->size;
  99. if (!silent) ESP_LOGD(TAG, "NumDimension: %d", numdim);
  100. int sizeofdim;
  101. for (int j = 0; j < numdim; ++j)
  102. {
  103. sizeofdim = output2->dims->data[j];
  104. if (!silent) ESP_LOGD(TAG, "SizeOfDimension %d: %d", j, sizeofdim);
  105. }
  106. float fo;
  107. // Process the inference results.
  108. int numeroutput = output2->dims->data[1];
  109. for (int i = 0; i < numeroutput; ++i)
  110. {
  111. fo = output2->data.f[i];
  112. if (!silent) ESP_LOGD(TAG, "Result %d: %f", i, fo);
  113. }
  114. return numeroutput;
  115. }
  116. void CTfLiteClass::Invoke()
  117. {
  118. if (interpreter != nullptr)
  119. interpreter->Invoke();
  120. }
  121. bool CTfLiteClass::LoadInputImageBasis(CImageBasis *rs)
  122. {
  123. #ifdef DEBUG_DETAIL_ON
  124. LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - Start");
  125. #endif
  126. unsigned int w = rs->width;
  127. unsigned int h = rs->height;
  128. unsigned char red, green, blue;
  129. // ESP_LOGD(TAG, "Image: %s size: %d x %d\n", _fn.c_str(), w, h);
  130. input_i = 0;
  131. float* input_data_ptr = (interpreter->input(0))->data.f;
  132. for (int y = 0; y < h; ++y)
  133. for (int x = 0; x < w; ++x)
  134. {
  135. red = rs->GetPixelColor(x, y, 0);
  136. green = rs->GetPixelColor(x, y, 1);
  137. blue = rs->GetPixelColor(x, y, 2);
  138. *(input_data_ptr) = (float) red;
  139. input_data_ptr++;
  140. *(input_data_ptr) = (float) green;
  141. input_data_ptr++;
  142. *(input_data_ptr) = (float) blue;
  143. input_data_ptr++;
  144. }
  145. #ifdef DEBUG_DETAIL_ON
  146. LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - done");
  147. #endif
  148. return true;
  149. }
  150. bool CTfLiteClass::MakeAllocate()
  151. {
  152. if (!ownsSharedMemoryLease || tensor_arena == NULL || model == nullptr) {
  153. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "MakeAllocate: Tensor Arena lease or model is unavailable");
  154. return false;
  155. }
  156. MakeStaticResolver();
  157. #ifdef DEBUG_DETAIL_ON
  158. LogFile.WriteHeapInfo("CTLiteClass::Alloc start");
  159. #endif
  160. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::MakeAllocate");
  161. delete this->interpreter;
  162. this->interpreter = new (std::nothrow) tflite::MicroInterpreter(
  163. this->model, resolver, this->tensor_arena, this->kTensorArenaSize);
  164. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trying to load the model. If it crashes here, it is most likely due to a corrupted model!");
  165. if (this->interpreter == nullptr) {
  166. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "new tflite::MicroInterpreter failed");
  167. LogFile.WriteHeapInfo("CTfLiteClass::MakeAllocate-new tflite::MicroInterpreter failed");
  168. return false;
  169. }
  170. const TfLiteStatus allocate_status = this->interpreter->AllocateTensors();
  171. if (allocate_status != kTfLiteOk) {
  172. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "AllocateTensors() failed");
  173. delete this->interpreter;
  174. this->interpreter = nullptr;
  175. return false;
  176. }
  177. #ifdef DEBUG_DETAIL_ON
  178. LogFile.WriteHeapInfo("CTLiteClass::Alloc done");
  179. #endif
  180. return true;
  181. }
  182. void CTfLiteClass::GetInputTensorSize()
  183. {
  184. #ifdef DEBUG_DETAIL_ON
  185. float *zw = this->input;
  186. int test = sizeof(zw);
  187. ESP_LOGD(TAG, "Input Tensor Dimension: %d", test);
  188. #endif
  189. }
  190. long CTfLiteClass::GetFileSize(std::string filename)
  191. {
  192. struct stat stat_buf;
  193. long rc = -1;
  194. FILE *pFile = fopen(filename.c_str(), "rb"); // previously only "rb
  195. if (pFile != NULL)
  196. {
  197. rc = stat(filename.c_str(), &stat_buf);
  198. fclose(pFile);
  199. }
  200. return rc == 0 ? stat_buf.st_size : -1;
  201. }
  202. bool CTfLiteClass::ReadFileToModel(std::string _fn)
  203. {
  204. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::ReadFileToModel: " + _fn);
  205. if (!ownsSharedMemoryLease || tensor_arena == NULL) {
  206. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Tensor Arena shared-memory lease was not acquired");
  207. return false;
  208. }
  209. const long size = GetFileSize(_fn);
  210. if (size <= 0) {
  211. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Model file is missing or empty: " + _fn);
  212. return false;
  213. }
  214. if (static_cast<unsigned long>(size) > static_cast<unsigned long>(MAX_MODEL_SIZE)) {
  215. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Model file is larger than the reserved shared model region: " + _fn);
  216. return false;
  217. }
  218. FILE *pFile = fopen(_fn.c_str(), "rb");
  219. if (pFile == NULL) {
  220. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Could not open model file " + _fn);
  221. return false;
  222. }
  223. if (!modelMemoryClaimed) {
  224. modelfile = static_cast<unsigned char*>(psram_get_shared_model_memory());
  225. modelMemoryClaimed = (modelfile != NULL);
  226. }
  227. if (modelfile == NULL) {
  228. fclose(pFile);
  229. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Unable to claim shared model memory");
  230. LogFile.WriteHeapInfo("CTfLiteClass::ReadFileToModel");
  231. return false;
  232. }
  233. #ifdef DEBUG_DETAIL_ON
  234. LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile start");
  235. #endif
  236. const size_t bytesRead = fread(modelfile, 1, static_cast<size_t>(size), pFile);
  237. const int closeResult = fclose(pFile);
  238. if (bytesRead != static_cast<size_t>(size) || closeResult != 0) {
  239. model = nullptr;
  240. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ReadFileToModel: Short read or close error while loading " + _fn);
  241. return false;
  242. }
  243. #ifdef DEBUG_DETAIL_ON
  244. LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful");
  245. #endif
  246. return true;
  247. }
  248. bool CTfLiteClass::LoadModel(std::string _fn)
  249. {
  250. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::LoadModel");
  251. if (!ReadFileToModel(_fn.c_str())) {
  252. return false;
  253. }
  254. model = tflite::GetModel(modelfile);
  255. if(model == nullptr)
  256. return false;
  257. return true;
  258. }
  259. CTfLiteClass::CTfLiteClass()
  260. {
  261. this->ownsSharedMemoryLease = false;
  262. this->modelMemoryClaimed = false;
  263. this->model = nullptr;
  264. this->modelfile = NULL;
  265. this->interpreter = nullptr;
  266. this->input = nullptr;
  267. this->output = nullptr;
  268. this->kTensorArenaSize = TENSOR_ARENA_SIZE;
  269. this->tensor_arena = static_cast<uint8_t*>(psram_get_shared_tensor_arena_memory());
  270. this->ownsSharedMemoryLease = (this->tensor_arena != NULL);
  271. if (!this->ownsSharedMemoryLease) {
  272. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire shared Tensor Arena memory");
  273. LogFile.WriteHeapInfo("CTfLiteClass constructor");
  274. }
  275. }
  276. CTfLiteClass::~CTfLiteClass()
  277. {
  278. delete this->interpreter;
  279. this->interpreter = nullptr;
  280. if (ownsSharedMemoryLease) {
  281. psram_free_shared_tensor_arena_and_model_memory();
  282. ownsSharedMemoryLease = false;
  283. modelMemoryClaimed = false;
  284. tensor_arena = nullptr;
  285. modelfile = nullptr;
  286. }
  287. }