CTfLiteClass.cpp 12 KB

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