CTfLiteClass.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. #include "defines.h"
  2. #include "CTfLiteClass.h"
  3. #include "ClassLogFile.h"
  4. #include "Helper.h"
  5. #include "psram.h"
  6. #include "esp_log.h"
  7. #include <sys/stat.h>
  8. static const char *TAG = "TFLITE";
  9. CTfLiteClass::CTfLiteClass()
  10. {
  11. model = nullptr;
  12. modelfile = NULL;
  13. interpreter = nullptr;
  14. input = nullptr;
  15. output = nullptr;
  16. kTensorArenaSize = TENSOR_ARENA_SIZE;
  17. tensor_arena = (uint8_t *)psram_get_shared_tensor_arena_memory();
  18. }
  19. CTfLiteClass::~CTfLiteClass()
  20. {
  21. delete interpreter;
  22. psram_free_shared_tensor_arena_and_model_memory();
  23. }
  24. bool CTfLiteClass::MakeStaticResolver(void)
  25. {
  26. if (resolver.AddFullyConnected() != kTfLiteOk)
  27. {
  28. ESP_LOGE(TAG, "load AddFullyConnected() failed");
  29. return false;
  30. }
  31. if (resolver.AddReshape() != kTfLiteOk)
  32. {
  33. ESP_LOGE(TAG, "load AddReshape() failed");
  34. return false;
  35. }
  36. if (resolver.AddSoftmax() != kTfLiteOk)
  37. {
  38. ESP_LOGE(TAG, "load AddSoftmax() failed");
  39. return false;
  40. }
  41. if (resolver.AddConv2D() != kTfLiteOk)
  42. {
  43. ESP_LOGE(TAG, "load AddConv2D() failed");
  44. return false;
  45. }
  46. if (resolver.AddMaxPool2D() != kTfLiteOk)
  47. {
  48. ESP_LOGE(TAG, "load AddMaxPool2D() failed");
  49. return false;
  50. }
  51. if (resolver.AddQuantize() != kTfLiteOk)
  52. {
  53. ESP_LOGE(TAG, "load AddQuantize() failed");
  54. return false;
  55. }
  56. if (resolver.AddMul() != kTfLiteOk)
  57. {
  58. ESP_LOGE(TAG, "load AddMul() failed");
  59. return false;
  60. }
  61. if (resolver.AddAdd() != kTfLiteOk)
  62. {
  63. ESP_LOGE(TAG, "load AddAdd() failed");
  64. return false;
  65. }
  66. if (resolver.AddLeakyRelu() != kTfLiteOk)
  67. {
  68. ESP_LOGE(TAG, "load AddLeakyRelu() failed");
  69. return false;
  70. }
  71. if (resolver.AddDequantize() != kTfLiteOk)
  72. {
  73. ESP_LOGE(TAG, "load AddDequantize() failed");
  74. return false;
  75. }
  76. return true;
  77. }
  78. float CTfLiteClass::GetOutputValue(int nr)
  79. {
  80. TfLiteTensor *output2 = interpreter->output(0);
  81. int numer_output = output2->dims->data[1];
  82. if ((nr + 1) > numer_output)
  83. {
  84. return -1000;
  85. }
  86. return output2->data.f[nr];
  87. }
  88. int CTfLiteClass::GetClassFromImageBasis(CImageBasis *rs)
  89. {
  90. if (!LoadInputImageBasis(rs))
  91. {
  92. return -1000;
  93. }
  94. Invoke();
  95. return GetOutClassification();
  96. }
  97. int CTfLiteClass::GetOutClassification(int _von, int _bis)
  98. {
  99. TfLiteTensor *output2 = interpreter->output(0);
  100. float zw_max;
  101. float zw;
  102. int zw_class;
  103. if (output2 == NULL)
  104. {
  105. return -1;
  106. }
  107. int numeroutput = output2->dims->data[1];
  108. // ESP_LOGD(TAG, "number output neurons: %d", numeroutput);
  109. if (_bis == -1)
  110. {
  111. _bis = numeroutput - 1;
  112. }
  113. if (_von == -1)
  114. {
  115. _von = 0;
  116. }
  117. if (_bis >= numeroutput)
  118. {
  119. ESP_LOGD(TAG, "NUMBER OF OUTPUT NEURONS does not match required classification!");
  120. return -1;
  121. }
  122. zw_max = output2->data.f[_von];
  123. zw_class = _von;
  124. for (int i = _von + 1; i <= _bis; ++i)
  125. {
  126. zw = output2->data.f[i];
  127. if (zw > zw_max)
  128. {
  129. zw_max = zw;
  130. zw_class = i;
  131. }
  132. }
  133. return (zw_class - _von);
  134. }
  135. void CTfLiteClass::GetInputDimension(bool silent = false)
  136. {
  137. TfLiteTensor *input2 = interpreter->input(0);
  138. int numdim = input2->dims->size;
  139. if (!silent)
  140. {
  141. ESP_LOGD(TAG, "NumDimension: %d", numdim);
  142. }
  143. int sizeofdim;
  144. for (int j = 0; j < numdim; ++j)
  145. {
  146. sizeofdim = input2->dims->data[j];
  147. if (!silent)
  148. {
  149. ESP_LOGD(TAG, "SizeOfDimension %d: %d", j, sizeofdim);
  150. }
  151. if (j == 1)
  152. {
  153. im_height = sizeofdim;
  154. }
  155. if (j == 2)
  156. {
  157. im_width = sizeofdim;
  158. }
  159. if (j == 3)
  160. {
  161. im_channel = sizeofdim;
  162. }
  163. }
  164. }
  165. int CTfLiteClass::ReadInputDimenstion(int _dim)
  166. {
  167. if (_dim == 0)
  168. {
  169. return im_width;
  170. }
  171. if (_dim == 1)
  172. {
  173. return im_height;
  174. }
  175. if (_dim == 2)
  176. {
  177. return im_channel;
  178. }
  179. return -1;
  180. }
  181. int CTfLiteClass::GetAnzOutPut(bool silent)
  182. {
  183. TfLiteTensor *output2 = interpreter->output(0);
  184. int numdim = output2->dims->size;
  185. if (!silent)
  186. {
  187. ESP_LOGD(TAG, "NumDimension: %d", numdim);
  188. }
  189. int sizeofdim;
  190. for (int j = 0; j < numdim; ++j)
  191. {
  192. sizeofdim = output2->dims->data[j];
  193. if (!silent)
  194. {
  195. ESP_LOGD(TAG, "SizeOfDimension %d: %d", j, sizeofdim);
  196. }
  197. }
  198. float fo;
  199. // Process the inference results.
  200. int numeroutput = output2->dims->data[1];
  201. for (int i = 0; i < numeroutput; ++i)
  202. {
  203. fo = output2->data.f[i];
  204. if (!silent)
  205. {
  206. ESP_LOGD(TAG, "Result %d: %f", i, fo);
  207. }
  208. }
  209. return numeroutput;
  210. }
  211. void CTfLiteClass::Invoke()
  212. {
  213. if (interpreter != nullptr)
  214. {
  215. interpreter->Invoke();
  216. }
  217. }
  218. bool CTfLiteClass::LoadInputImageBasis(CImageBasis *rs)
  219. {
  220. unsigned int w = rs->width;
  221. unsigned int h = rs->height;
  222. unsigned char red, green, blue;
  223. // ESP_LOGD(TAG, "Image: %s size: %d x %d\n", _fn.c_str(), w, h);
  224. input_i = 0;
  225. float *input_data_ptr = (interpreter->input(0))->data.f;
  226. for (int y = 0; y < h; ++y)
  227. {
  228. for (int x = 0; x < w; ++x)
  229. {
  230. red = rs->GetPixelColor(x, y, 0);
  231. green = rs->GetPixelColor(x, y, 1);
  232. blue = rs->GetPixelColor(x, y, 2);
  233. *(input_data_ptr) = (float)red;
  234. input_data_ptr++;
  235. *(input_data_ptr) = (float)green;
  236. input_data_ptr++;
  237. *(input_data_ptr) = (float)blue;
  238. input_data_ptr++;
  239. }
  240. }
  241. return true;
  242. }
  243. bool CTfLiteClass::MakeAllocate(void)
  244. {
  245. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::MakeAllocate");
  246. if (!MakeStaticResolver())
  247. {
  248. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::MakeAllocate - resolver could not be loaded!");
  249. return false;
  250. }
  251. if (!model)
  252. {
  253. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::MakeAllocate - no model loaded!");
  254. return false;
  255. }
  256. if (model->version() != TFLITE_SCHEMA_VERSION)
  257. {
  258. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "The selected model does not match the tflite schema version!");
  259. return false;
  260. }
  261. if (!tensor_arena)
  262. {
  263. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::MakeAllocate - tensor_arena not allocate");
  264. return false;
  265. }
  266. interpreter = new tflite::MicroInterpreter(model, resolver, tensor_arena, kTensorArenaSize);
  267. // LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trying to load the model. If it crashes here, it ist most likely due to a corrupted model!");
  268. if (interpreter)
  269. {
  270. TfLiteStatus allocate_status = interpreter->AllocateTensors();
  271. if (allocate_status != kTfLiteOk)
  272. {
  273. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "AllocateTensors() failed");
  274. GetInputDimension();
  275. return false;
  276. }
  277. }
  278. else
  279. {
  280. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "new tflite::MicroInterpreter failed");
  281. LogFile.WriteHeapInfo("CTfLiteClass::MakeAllocate-new tflite::MicroInterpreter failed");
  282. return false;
  283. }
  284. return true;
  285. }
  286. long CTfLiteClass::GetFileSize(std::string filename)
  287. {
  288. struct stat stat_buf;
  289. long rc = -1;
  290. FILE *pFile = fopen(filename.c_str(), "rb"); // previously only "rb
  291. if (pFile != NULL)
  292. {
  293. rc = stat(filename.c_str(), &stat_buf);
  294. fclose(pFile);
  295. }
  296. return (rc == 0 ? stat_buf.st_size : -1);
  297. }
  298. bool CTfLiteClass::ReadFileToModel(std::string filename)
  299. {
  300. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::ReadFileToModel: " + filename);
  301. long size = GetFileSize(filename);
  302. if (size == -1)
  303. {
  304. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Model file doesn't exist: " + filename + "!");
  305. return false;
  306. }
  307. else if (size > MAX_MODEL_SIZE)
  308. {
  309. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to load model '" + filename + "'! It does not fit in the reserved shared memory in PSRAM!");
  310. return false;
  311. }
  312. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Loading Model " + filename + " /size: " + std::to_string(size) + " bytes...");
  313. modelfile = (unsigned char *)psram_get_shared_model_memory();
  314. if (modelfile != NULL)
  315. {
  316. FILE *pFile = fopen(filename.c_str(), "rb"); // previously only "rb
  317. if (pFile != NULL)
  318. {
  319. fread(modelfile, 1, size, pFile);
  320. fclose(pFile);
  321. return true;
  322. }
  323. else
  324. {
  325. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Model does not exist");
  326. return false;
  327. }
  328. }
  329. else
  330. {
  331. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Can't allocate enough memory: " + std::to_string(size));
  332. LogFile.WriteHeapInfo("CTfLiteClass::ReadFileToModel");
  333. return false;
  334. }
  335. }
  336. bool CTfLiteClass::LoadModel(std::string filename)
  337. {
  338. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::LoadModel");
  339. if (!ReadFileToModel(filename.c_str()))
  340. {
  341. return false;
  342. }
  343. model = tflite::GetModel(modelfile);
  344. if (model == nullptr)
  345. {
  346. return false;
  347. }
  348. return true;
  349. }