CTfLiteClass.cpp 11 KB

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