ClassFlowCNNGeneral.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. #include "ClassFlowCNNGeneral.h"
  2. #include <math.h>
  3. #include <iomanip>
  4. #include <sys/types.h>
  5. #include <sstream> // std::stringstream
  6. #include "CTfLiteClass.h"
  7. #include "ClassLogFile.h"
  8. #include "esp_log.h"
  9. #include "../../include/defines.h"
  10. static const char* TAG = "CNN";
  11. //#ifdef CONFIG_HEAP_TRACING_STANDALONE
  12. #ifdef HEAP_TRACING_CLASS_FLOW_CNN_GENERAL_DO_ALING_AND_CUT
  13. #include <esp_heap_trace.h>
  14. #define NUM_RECORDS 300
  15. static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
  16. #endif
  17. ClassFlowCNNGeneral::ClassFlowCNNGeneral(ClassFlowAlignment *_flowalign, t_CNNType _cnntype) : ClassFlowImage(NULL, TAG)
  18. {
  19. string cnnmodelfile = "";
  20. modelxsize = 1;
  21. modelysize = 1;
  22. CNNGoodThreshold = 0.0;
  23. ListFlowControll = NULL;
  24. previousElement = NULL;
  25. SaveAllFiles = false;
  26. disabled = false;
  27. isLogImageSelect = false;
  28. CNNType = AutoDetect;
  29. CNNType = _cnntype;
  30. flowpostalignment = _flowalign;
  31. imagesRetention = 5;
  32. }
  33. string ClassFlowCNNGeneral::getReadout(int _analog = 0, bool _extendedResolution, int prev, float _before_narrow_Analog, float analogDigitalTransitionStart)
  34. {
  35. string result = "";
  36. if (GENERAL[_analog]->ROI.size() == 0)
  37. return result;
  38. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout _analog=" + std::to_string(_analog) + ", _extendedResolution=" + std::to_string(_extendedResolution) + ", prev=" + std::to_string(prev));
  39. if (CNNType == Analogue || CNNType == Analogue100)
  40. {
  41. float number = GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float;
  42. int result_after_decimal_point = ((int) floor(number * 10) + 10) % 10;
  43. prev = PointerEvalAnalogNew(GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float, prev);
  44. // LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout(analog) number=" + std::to_string(number) + ", result_after_decimal_point=" + std::to_string(result_after_decimal_point) + ", prev=" + std::to_string(prev));
  45. result = std::to_string(prev);
  46. if (_extendedResolution)
  47. result = result + std::to_string(result_after_decimal_point);
  48. for (int i = GENERAL[_analog]->ROI.size() - 2; i >= 0; --i)
  49. {
  50. prev = PointerEvalAnalogNew(GENERAL[_analog]->ROI[i]->result_float, prev);
  51. result = std::to_string(prev) + result;
  52. }
  53. return result;
  54. }
  55. if (CNNType == Digital)
  56. {
  57. for (int i = 0; i < GENERAL[_analog]->ROI.size(); ++i)
  58. {
  59. if (GENERAL[_analog]->ROI[i]->result_klasse >= 10)
  60. result = result + "N";
  61. else
  62. result = result + std::to_string(GENERAL[_analog]->ROI[i]->result_klasse);
  63. }
  64. return result;
  65. }
  66. if ((CNNType == DoubleHyprid10) || (CNNType == Digital100))
  67. {
  68. float number = GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float;
  69. if (number >= 0) // NaN?
  70. {
  71. if (_extendedResolution) // is only set if it is the first digit (no analogue before!)
  72. {
  73. int result_after_decimal_point = ((int) floor(number * 10)) % 10;
  74. int result_before_decimal_point = ((int) floor(number)) % 10;
  75. result = std::to_string(result_before_decimal_point) + std::to_string(result_after_decimal_point);
  76. prev = result_before_decimal_point;
  77. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout(dig100-ext) result_before_decimal_point=" + std::to_string(result_before_decimal_point) + ", result_after_decimal_point=" + std::to_string(result_after_decimal_point) + ", prev=" + std::to_string(prev));
  78. }
  79. else
  80. {
  81. if (_before_narrow_Analog >= 0)
  82. prev = PointerEvalHybridNew(GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float, _before_narrow_Analog, prev, true, analogDigitalTransitionStart);
  83. else
  84. prev = PointerEvalHybridNew(GENERAL[_analog]->ROI[GENERAL[_analog]->ROI.size() - 1]->result_float, prev, prev);
  85. result = std::to_string(prev);
  86. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout(dig100) prev=" + std::to_string(prev));
  87. }
  88. }
  89. else
  90. {
  91. result = "N";
  92. if (_extendedResolution && (CNNType != Digital))
  93. result = "NN";
  94. }
  95. for (int i = GENERAL[_analog]->ROI.size() - 2; i >= 0; --i)
  96. {
  97. if (GENERAL[_analog]->ROI[i]->result_float >= 0)
  98. {
  99. prev = PointerEvalHybridNew(GENERAL[_analog]->ROI[i]->result_float, GENERAL[_analog]->ROI[i+1]->result_float, prev);
  100. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout#PointerEvalHybridNew()= " + std::to_string(prev));
  101. result = std::to_string(prev) + result;
  102. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout#result= " + result);
  103. }
  104. else
  105. {
  106. prev = -1;
  107. result = "N" + result;
  108. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "getReadout(result_float<0 /'N') result_float=" + std::to_string(GENERAL[_analog]->ROI[i]->result_float));
  109. }
  110. }
  111. return result;
  112. }
  113. return result;
  114. }
  115. /**
  116. * @brief Determines the number of an ROI in connection with previous ROI results
  117. *
  118. * @param number: is the current ROI as float value from recognition
  119. * @param number_of_predecessors: is the last (lower) ROI as float from recognition
  120. * @param eval_predecessors: is the evaluated number. Sometimes a much lower value can change higer values
  121. * example: 9.8, 9.9, 0.1
  122. * 0.1 => 0 (eval_predecessors)
  123. * The 0 makes a 9.9 to 0 (eval_predecessors)
  124. * The 0 makes a 9.8 to 0
  125. * @param Analog_Predecessors false/true if the last ROI is an analog or digital ROI (default=false)
  126. * runs in special handling because analog is much less precise
  127. * @param digitalAnalogTransitionStart start of the transitionlogic begins on number_of_predecessor (default=9.2)
  128. *
  129. * @return int the determined number of the current ROI
  130. */
  131. int ClassFlowCNNGeneral::PointerEvalHybridNew(float number, float number_of_predecessors, int eval_predecessors, bool Analog_Predecessors, float digitalAnalogTransitionStart)
  132. {
  133. int result;
  134. int result_after_decimal_point = ((int) floor(number * 10)) % 10;
  135. int result_before_decimal_point = ((int) floor(number) + 10) % 10;
  136. if (eval_predecessors < 0)
  137. {
  138. // on first digit is no spezial logic for transition needed
  139. // we use the recognition as given. The result is the int value of the recognition
  140. // add precisition of 2 digits and round before trunc
  141. result = (int) ((int) trunc(round((number+10 % 10)*100)) ) / 100;
  142. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalHybridNew - No predecessor - Result = " + std::to_string(result) +
  143. " number: " + std::to_string(number) + " number_of_predecessors = " + std::to_string(number_of_predecessors)+ " eval_predecessors = " + std::to_string(eval_predecessors) + " Digital_Uncertainty = " + std::to_string(Digital_Uncertainty));
  144. return result;
  145. }
  146. if (Analog_Predecessors)
  147. {
  148. result = PointerEvalAnalogToDigitNew(number, number_of_predecessors, eval_predecessors, digitalAnalogTransitionStart);
  149. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalHybridNew - Analog predecessor, evaluation over PointerEvalAnalogNew = " + std::to_string(result) +
  150. " number: " + std::to_string(number) + " number_of_predecessors = " + std::to_string(number_of_predecessors)+ " eval_predecessors = " + std::to_string(eval_predecessors) + " Digital_Uncertainty = " + std::to_string(Digital_Uncertainty));
  151. return result;
  152. }
  153. if ((number_of_predecessors >= Digital_Transition_Area_Predecessor ) && (number_of_predecessors <= (10.0 - Digital_Transition_Area_Predecessor)))
  154. {
  155. // no digit change, because predecessor is far enough away (0+/-DigitalTransitionRangePredecessor) --> number is rounded
  156. if ((result_after_decimal_point <= DigitalBand) || (result_after_decimal_point >= (10-DigitalBand))) // Band around the digit --> Round off, as digit reaches inaccuracy in the frame
  157. result = ((int) round(number) + 10) % 10;
  158. else
  159. result = ((int) trunc(number) + 10) % 10;
  160. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalHybridNew - NO analogue predecessor, no change of digits, as pre-decimal point far enough away = " + std::to_string(result) +
  161. " number: " + std::to_string(number) + " number_of_predecessors = " + std::to_string(number_of_predecessors)+ " eval_predecessors = " + std::to_string(eval_predecessors) + " Digital_Uncertainty = " + std::to_string(Digital_Uncertainty));
  162. return result;
  163. }
  164. if (eval_predecessors <= 1) // Zero crossing at the predecessor has taken place (! evaluation via Prev_value and not number!) --> round up here (2.8 --> 3, but also 3.1 --> 3)
  165. {
  166. // We simply assume that the current digit after the zero crossing of the predecessor
  167. // has passed through at least half (x.5)
  168. if (result_after_decimal_point > 5)
  169. // The current digit does not yet have a zero crossing, but the predecessor does..
  170. result = (result_before_decimal_point + 1) % 10;
  171. else
  172. // Act. digit and predecessor have zero crossing
  173. result = result_before_decimal_point % 10;
  174. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalHybridNew - NO analogue predecessor, zero crossing has taken placen = " + std::to_string(result) +
  175. " number: " + std::to_string(number) + " number_of_predecessors = " + std::to_string(number_of_predecessors)+ " eval_predecessors = " + std::to_string(eval_predecessors) + " Digital_Uncertainty = " + std::to_string(Digital_Uncertainty));
  176. return result;
  177. }
  178. // remains only >= 9.x --> no zero crossing yet --> 2.8 --> 2,
  179. // and from 9.7(DigitalTransitionRangeLead) 3.1 --> 2
  180. // everything >=x.4 can be considered as current number in transition. With 9.x predecessor the current
  181. // number can still be x.6 - x.7.
  182. // Preceding (else - branch) does not already happen from 9.
  183. if (Digital_Transition_Area_Forward>=number_of_predecessors || result_after_decimal_point >= 4)
  184. // The current digit, like the previous digit, does not yet have a zero crossing.
  185. result = result_before_decimal_point % 10;
  186. else
  187. // current digit precedes the smaller digit (9.x). So already >=x.0 while the previous digit has not yet
  188. // has no zero crossing. Therefore, it is reduced by 1.
  189. result = (result_before_decimal_point - 1 + 10) % 10;
  190. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalHybridNew - O analogue predecessor, >= 9.5 --> no zero crossing yet = " + std::to_string(result) +
  191. " number: " + std::to_string(number) + " number_of_predecessors = " + std::to_string(number_of_predecessors)+ " eval_predecessors = " + std::to_string(eval_predecessors) + " Digital_Uncertainty = " + std::to_string(Digital_Uncertainty) + " result_after_decimal_point = " + std::to_string(result_after_decimal_point));
  192. return result;
  193. }
  194. int ClassFlowCNNGeneral::PointerEvalAnalogToDigitNew(float number, float numeral_preceder, int eval_predecessors, float analogDigitalTransitionStart)
  195. {
  196. int result;
  197. int result_after_decimal_point = ((int) floor(number * 10)) % 10;
  198. int result_before_decimal_point = ((int) floor(number) + 10) % 10;
  199. bool roundedUp = false;
  200. // Within the digital inequalities
  201. if ((result_after_decimal_point >= (10-Digital_Uncertainty * 10)) // Band around the digit --> Round off, as digit reaches inaccuracy in the frame
  202. || (eval_predecessors <= 4 && result_after_decimal_point>=6)) { // or digit runs after (analogue =0..4, digit >=6)
  203. result = (int) (round(number) + 10) % 10;
  204. roundedUp = true;
  205. // before/ after decimal point, because we adjust the number based on the uncertainty.
  206. result_after_decimal_point = ((int) floor(result * 10)) % 10;
  207. result_before_decimal_point = ((int) floor(result) + 10) % 10;
  208. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogToDigitNew - Digital Uncertainty - Result = " + std::to_string(result) +
  209. " number: " + std::to_string(number) + " numeral_preceder: " + std::to_string(numeral_preceder) +
  210. " erg before comma: " + std::to_string(result_before_decimal_point) +
  211. " erg after comma: " + std::to_string(result_after_decimal_point));
  212. } else {
  213. result = (int) ((int) trunc(number) + 10) % 10;
  214. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogToDigitNew - NO digital Uncertainty - Result = " + std::to_string(result) +
  215. " number: " + std::to_string(number) + " numeral_preceder = " + std::to_string(numeral_preceder));
  216. }
  217. // No zero crossing has taken place.
  218. // Only eval_predecessors used because numeral_preceder could be wrong here.
  219. // numeral_preceder<=0.1 & eval_predecessors=9 corresponds to analogue was reset because of previous analogue that are not yet at 0.
  220. if ((eval_predecessors>=6 && (numeral_preceder>analogDigitalTransitionStart || numeral_preceder<=0.2) && roundedUp))
  221. {
  222. result = ((result_before_decimal_point+10) - 1) % 10;
  223. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogToDigitNew - Nulldurchgang noch nicht stattgefunden = " + std::to_string(result) +
  224. " number: " + std::to_string(number) +
  225. " numeral_preceder = " + std::to_string(numeral_preceder) +
  226. " eerg after comma = " + std::to_string(result_after_decimal_point));
  227. }
  228. return result;
  229. }
  230. int ClassFlowCNNGeneral::PointerEvalAnalogNew(float number, int numeral_preceder)
  231. {
  232. float number_min, number_max;
  233. int result;
  234. if (numeral_preceder == -1)
  235. {
  236. result = (int) floor(number);
  237. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogNew - No predecessor - Result = " + std::to_string(result) +
  238. " number: " + std::to_string(number) + " numeral_preceder = " + std::to_string(numeral_preceder) + " Analog_error = " + std::to_string(Analog_error));
  239. return result;
  240. }
  241. number_min = number - Analog_error / 10.0;
  242. number_max = number + Analog_error / 10.0;
  243. if ((int) floor(number_max) - (int) floor(number_min) != 0)
  244. {
  245. if (numeral_preceder <= Analog_error)
  246. {
  247. result = ((int) floor(number_max) + 10) % 10;
  248. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogNew - number ambiguous, correction upwards - result = " + std::to_string(result) +
  249. " number: " + std::to_string(number) + " numeral_preceder = " + std::to_string(numeral_preceder) + " Analog_error = " + std::to_string(Analog_error));
  250. return result;
  251. }
  252. if (numeral_preceder >= 10 - Analog_error)
  253. {
  254. result = ((int) floor(number_min) + 10) % 10;
  255. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogNew - number ambiguous, downward correction - result = " + std::to_string(result) +
  256. " number: " + std::to_string(number) + " numeral_preceder = " + std::to_string(numeral_preceder) + " Analog_error = " + std::to_string(Analog_error));
  257. return result;
  258. }
  259. }
  260. result = ((int) floor(number) + 10) % 10;
  261. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "PointerEvalAnalogNew - number unambiguous, no correction necessary - result = " + std::to_string(result) +
  262. " number: " + std::to_string(number) + " numeral_preceder = " + std::to_string(numeral_preceder) + " Analog_error = " + std::to_string(Analog_error));
  263. return result;
  264. }
  265. bool ClassFlowCNNGeneral::ReadParameter(FILE* pfile, string& aktparamgraph)
  266. {
  267. std::vector<string> splitted;
  268. aktparamgraph = trim(aktparamgraph);
  269. if (aktparamgraph.size() == 0)
  270. if (!this->GetNextParagraph(pfile, aktparamgraph))
  271. return false;
  272. if ((toUpper(aktparamgraph) != "[ANALOG]") && (toUpper(aktparamgraph) != ";[ANALOG]")
  273. && (toUpper(aktparamgraph) != "[DIGIT]") && (toUpper(aktparamgraph) != ";[DIGIT]")
  274. && (toUpper(aktparamgraph) != "[DIGITS]") && (toUpper(aktparamgraph) != ";[DIGITS]")
  275. ) // Paragraph passt nicht
  276. return false;
  277. if (aktparamgraph[0] == ';')
  278. {
  279. disabled = true;
  280. while (getNextLine(pfile, &aktparamgraph) && !isNewParagraph(aktparamgraph));
  281. ESP_LOGD(TAG, "[Analog/Digit] is disabled!");
  282. return true;
  283. }
  284. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  285. {
  286. splitted = ZerlegeZeile(aktparamgraph);
  287. if ((toUpper(splitted[0]) == "ROIIMAGESLOCATION") && (splitted.size() > 1))
  288. {
  289. this->imagesLocation = "/sdcard" + splitted[1];
  290. this->isLogImage = true;
  291. }
  292. if ((toUpper(splitted[0]) == "LOGIMAGESELECT") && (splitted.size() > 1))
  293. {
  294. LogImageSelect = splitted[1];
  295. isLogImageSelect = true;
  296. }
  297. if ((toUpper(splitted[0]) == "ROIIMAGESRETENTION") && (splitted.size() > 1))
  298. {
  299. this->imagesRetention = std::stoi(splitted[1]);
  300. }
  301. if ((toUpper(splitted[0]) == "MODEL") && (splitted.size() > 1))
  302. {
  303. this->cnnmodelfile = splitted[1];
  304. }
  305. if ((toUpper(splitted[0]) == "CNNGOODTHRESHOLD") && (splitted.size() > 1))
  306. {
  307. CNNGoodThreshold = std::stof(splitted[1]);
  308. }
  309. if (splitted.size() >= 5)
  310. {
  311. general* _analog = GetGENERAL(splitted[0], true);
  312. roi* neuroi = _analog->ROI[_analog->ROI.size()-1];
  313. neuroi->posx = std::stoi(splitted[1]);
  314. neuroi->posy = std::stoi(splitted[2]);
  315. neuroi->deltax = std::stoi(splitted[3]);
  316. neuroi->deltay = std::stoi(splitted[4]);
  317. neuroi->CCW = false;
  318. if (splitted.size() >= 6)
  319. {
  320. neuroi->CCW = toUpper(splitted[5]) == "TRUE";
  321. }
  322. neuroi->result_float = -1;
  323. neuroi->image = NULL;
  324. neuroi->image_org = NULL;
  325. }
  326. if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1))
  327. {
  328. if (toUpper(splitted[1]) == "TRUE")
  329. SaveAllFiles = true;
  330. }
  331. }
  332. if (!getNetworkParameter()) {
  333. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "An error occured on setting up the Network -> Disabling it!");
  334. disabled = true; // An error occured, disable this CNN!
  335. return false;
  336. }
  337. for (int _ana = 0; _ana < GENERAL.size(); ++_ana)
  338. for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i)
  339. {
  340. GENERAL[_ana]->ROI[i]->image = new CImageBasis("ROI " + GENERAL[_ana]->ROI[i]->name,
  341. modelxsize, modelysize, modelchannel);
  342. GENERAL[_ana]->ROI[i]->image_org = new CImageBasis("ROI " + GENERAL[_ana]->ROI[i]->name + " original",
  343. GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, 3);
  344. }
  345. return true;
  346. }
  347. general* ClassFlowCNNGeneral::FindGENERAL(string _name_number)
  348. {
  349. for (int i = 0; i < GENERAL.size(); ++i)
  350. if (GENERAL[i]->name == _name_number)
  351. return GENERAL[i];
  352. return NULL;
  353. }
  354. general* ClassFlowCNNGeneral::GetGENERAL(string _name, bool _create = true)
  355. {
  356. string _analog, _roi;
  357. int _pospunkt = _name.find_first_of(".");
  358. if (_pospunkt > -1)
  359. {
  360. _analog = _name.substr(0, _pospunkt);
  361. _roi = _name.substr(_pospunkt+1, _name.length() - _pospunkt - 1);
  362. }
  363. else
  364. {
  365. _analog = "default";
  366. _roi = _name;
  367. }
  368. general *_ret = NULL;
  369. for (int i = 0; i < GENERAL.size(); ++i)
  370. if (GENERAL[i]->name == _analog)
  371. _ret = GENERAL[i];
  372. if (!_create) // not found and should not be created
  373. return _ret;
  374. if (_ret == NULL)
  375. {
  376. _ret = new general;
  377. _ret->name = _analog;
  378. GENERAL.push_back(_ret);
  379. }
  380. roi* neuroi = new roi;
  381. neuroi->name = _roi;
  382. _ret->ROI.push_back(neuroi);
  383. ESP_LOGD(TAG, "GetGENERAL - GENERAL %s - roi %s - CCW: %d", _analog.c_str(), _roi.c_str(), neuroi->CCW);
  384. return _ret;
  385. }
  386. string ClassFlowCNNGeneral::getHTMLSingleStep(string host)
  387. {
  388. string result, zw;
  389. std::vector<HTMLInfo*> htmlinfo;
  390. result = "<p>Found ROIs: </p> <p><img src=\"" + host + "/img_tmp/alg_roi.jpg\"></p>\n";
  391. result = result + "Analog Pointers: <p> ";
  392. htmlinfo = GetHTMLInfo();
  393. for (int i = 0; i < htmlinfo.size(); ++i)
  394. {
  395. std::stringstream stream;
  396. stream << std::fixed << std::setprecision(1) << htmlinfo[i]->val;
  397. zw = stream.str();
  398. result = result + "<img src=\"" + host + "/img_tmp/" + htmlinfo[i]->filename + "\"> " + zw;
  399. delete htmlinfo[i];
  400. }
  401. htmlinfo.clear();
  402. return result;
  403. }
  404. bool ClassFlowCNNGeneral::doFlow(string time)
  405. {
  406. #ifdef HEAP_TRACING_CLASS_FLOW_CNN_GENERAL_DO_ALING_AND_CUT
  407. //register a buffer to record the memory trace
  408. ESP_ERROR_CHECK( heap_trace_init_standalone(trace_record, NUM_RECORDS) );
  409. // start tracing
  410. ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
  411. #endif
  412. if (disabled)
  413. return true;
  414. if (!doAlignAndCut(time)){
  415. return false;
  416. }
  417. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "doFlow after alignment");
  418. doNeuralNetwork(time);
  419. RemoveOldLogs();
  420. #ifdef HEAP_TRACING_CLASS_FLOW_CNN_GENERAL_DO_ALING_AND_CUT
  421. ESP_ERROR_CHECK( heap_trace_stop() );
  422. heap_trace_dump();
  423. #endif
  424. return true;
  425. }
  426. bool ClassFlowCNNGeneral::doAlignAndCut(string time)
  427. {
  428. if (disabled)
  429. return true;
  430. CAlignAndCutImage *caic = flowpostalignment->GetAlignAndCutImage();
  431. for (int _ana = 0; _ana < GENERAL.size(); ++_ana)
  432. for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i)
  433. {
  434. ESP_LOGD(TAG, "General %d - Align&Cut", i);
  435. caic->CutAndSave(GENERAL[_ana]->ROI[i]->posx, GENERAL[_ana]->ROI[i]->posy, GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, GENERAL[_ana]->ROI[i]->image_org);
  436. if (SaveAllFiles)
  437. {
  438. if (GENERAL[_ana]->name == "default")
  439. GENERAL[_ana]->ROI[i]->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
  440. else
  441. GENERAL[_ana]->ROI[i]->image_org->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
  442. }
  443. GENERAL[_ana]->ROI[i]->image_org->Resize(modelxsize, modelysize, GENERAL[_ana]->ROI[i]->image);
  444. if (SaveAllFiles)
  445. {
  446. if (GENERAL[_ana]->name == "default")
  447. GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
  448. else
  449. GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
  450. }
  451. }
  452. return true;
  453. }
  454. void ClassFlowCNNGeneral::DrawROI(CImageBasis *_zw)
  455. {
  456. if (_zw->ImageOkay())
  457. {
  458. if (CNNType == Analogue || CNNType == Analogue100)
  459. {
  460. int r = 0;
  461. int g = 255;
  462. int b = 0;
  463. for (int _ana = 0; _ana < GENERAL.size(); ++_ana)
  464. for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i)
  465. {
  466. _zw->drawRect(GENERAL[_ana]->ROI[i]->posx, GENERAL[_ana]->ROI[i]->posy, GENERAL[_ana]->ROI[i]->deltax, GENERAL[_ana]->ROI[i]->deltay, r, g, b, 1);
  467. _zw->drawEllipse( (int) (GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax/2), (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay/2), (int) (GENERAL[_ana]->ROI[i]->deltax/2), (int) (GENERAL[_ana]->ROI[i]->deltay/2), r, g, b, 2);
  468. _zw->drawLine((int) (GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax/2), (int) GENERAL[_ana]->ROI[i]->posy, (int) (GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax/2), (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay), r, g, b, 2);
  469. _zw->drawLine((int) GENERAL[_ana]->ROI[i]->posx, (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay/2), (int) GENERAL[_ana]->ROI[i]->posx + GENERAL[_ana]->ROI[i]->deltax, (int) (GENERAL[_ana]->ROI[i]->posy + GENERAL[_ana]->ROI[i]->deltay/2), r, g, b, 2);
  470. }
  471. }
  472. else
  473. {
  474. for (int _dig = 0; _dig < GENERAL.size(); ++_dig)
  475. for (int i = 0; i < GENERAL[_dig]->ROI.size(); ++i)
  476. _zw->drawRect(GENERAL[_dig]->ROI[i]->posx, GENERAL[_dig]->ROI[i]->posy, GENERAL[_dig]->ROI[i]->deltax, GENERAL[_dig]->ROI[i]->deltay, 0, 0, (255 - _dig*100), 2);
  477. }
  478. }
  479. }
  480. bool ClassFlowCNNGeneral::getNetworkParameter()
  481. {
  482. if (disabled)
  483. return true;
  484. CTfLiteClass *tflite = new CTfLiteClass;
  485. string zwcnn = "/sdcard" + cnnmodelfile;
  486. zwcnn = FormatFileName(zwcnn);
  487. ESP_LOGD(TAG, "%s", zwcnn.c_str());
  488. if (!tflite->LoadModel(zwcnn)) {
  489. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't load tflite model " + cnnmodelfile + " -> Init aborted!");
  490. LogFile.WriteHeapInfo("getNetworkParameter-LoadModel");
  491. delete tflite;
  492. return false;
  493. }
  494. if (!tflite->MakeAllocate()) {
  495. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tflite model -> Init aborted!");
  496. LogFile.WriteHeapInfo("getNetworkParameter-MakeAllocate");
  497. delete tflite;
  498. return false;
  499. }
  500. if (CNNType == AutoDetect)
  501. {
  502. tflite->GetInputDimension(false);
  503. modelxsize = tflite->ReadInputDimenstion(0);
  504. modelysize = tflite->ReadInputDimenstion(1);
  505. modelchannel = tflite->ReadInputDimenstion(2);
  506. int _anzoutputdimensions = tflite->GetAnzOutPut();
  507. switch (_anzoutputdimensions)
  508. {
  509. case 2:
  510. CNNType = Analogue;
  511. ESP_LOGD(TAG, "TFlite-Type set to Analogue");
  512. break;
  513. case 10:
  514. CNNType = DoubleHyprid10;
  515. ESP_LOGD(TAG, "TFlite-Type set to DoubleHyprid10");
  516. break;
  517. case 11:
  518. CNNType = Digital;
  519. ESP_LOGD(TAG, "TFlite-Type set to Digital");
  520. break;
  521. /* case 20:
  522. CNNType = DigitalHyprid10;
  523. ESP_LOGD(TAG, "TFlite-Type set to DigitalHyprid10");
  524. break;
  525. */
  526. // case 22:
  527. // CNNType = DigitalHyprid;
  528. // ESP_LOGD(TAG, "TFlite-Type set to DigitalHyprid");
  529. // break;
  530. case 100:
  531. if (modelxsize==32 && modelysize == 32) {
  532. CNNType = Analogue100;
  533. ESP_LOGD(TAG, "TFlite-Type set to Analogue100");
  534. } else {
  535. CNNType = Digital100;
  536. ESP_LOGD(TAG, "TFlite-Type set to Digital");
  537. }
  538. break;
  539. default:
  540. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tflite does not fit the firmware (outout_dimension=" + std::to_string(_anzoutputdimensions) + ")");
  541. }
  542. }
  543. delete tflite;
  544. return true;
  545. }
  546. bool ClassFlowCNNGeneral::doNeuralNetwork(string time)
  547. {
  548. if (disabled)
  549. return true;
  550. string logPath = CreateLogFolder(time);
  551. CTfLiteClass *tflite = new CTfLiteClass;
  552. string zwcnn = "/sdcard" + cnnmodelfile;
  553. zwcnn = FormatFileName(zwcnn);
  554. ESP_LOGD(TAG, "%s", zwcnn.c_str());
  555. if (!tflite->LoadModel(zwcnn)) {
  556. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't load tflite model " + cnnmodelfile + " -> Exec aborted this round!");
  557. LogFile.WriteHeapInfo("doNeuralNetwork-LoadModel");
  558. delete tflite;
  559. return false;
  560. }
  561. if (!tflite->MakeAllocate()) {
  562. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tfilte model -> Exec aborted this round!");
  563. LogFile.WriteHeapInfo("doNeuralNetwork-MakeAllocate");
  564. delete tflite;
  565. return false;
  566. }
  567. for (int n = 0; n < GENERAL.size(); ++n) // For each NUMBER
  568. {
  569. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Processing Number '" + GENERAL[n]->name + "'");
  570. for (int roi = 0; roi < GENERAL[n]->ROI.size(); ++roi) // For each ROI
  571. {
  572. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "ROI #" + std::to_string(roi) + " - TfLite");
  573. //ESP_LOGD(TAG, "General %d - TfLite", i);
  574. switch (CNNType) {
  575. case Analogue:
  576. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CNN Type: Analogue");
  577. {
  578. float f1, f2;
  579. f1 = 0; f2 = 0;
  580. tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);
  581. tflite->Invoke();
  582. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "After Invoke");
  583. f1 = tflite->GetOutputValue(0);
  584. f2 = tflite->GetOutputValue(1);
  585. float result = fmod(atan2(f1, f2) / (M_PI * 2) + 2, 1);
  586. if(GENERAL[n]->ROI[roi]->CCW)
  587. GENERAL[n]->ROI[roi]->result_float = 10 - (result * 10);
  588. else
  589. GENERAL[n]->ROI[roi]->result_float = result * 10;
  590. ESP_LOGD(TAG, "General result (Analog)%i - CCW: %d - %f", roi, GENERAL[n]->ROI[roi]->CCW, GENERAL[n]->ROI[roi]->result_float);
  591. if (isLogImage)
  592. LogImage(logPath, GENERAL[n]->ROI[roi]->name, &GENERAL[n]->ROI[roi]->result_float, NULL, time, GENERAL[n]->ROI[roi]->image_org);
  593. } break;
  594. case Digital:
  595. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CNN Type: Digital");
  596. {
  597. GENERAL[n]->ROI[roi]->result_klasse = 0;
  598. GENERAL[n]->ROI[roi]->result_klasse = tflite->GetClassFromImageBasis(GENERAL[n]->ROI[roi]->image);
  599. ESP_LOGD(TAG, "General result (Digit)%i: %d", roi, GENERAL[n]->ROI[roi]->result_klasse);
  600. if (isLogImage)
  601. {
  602. string _imagename = GENERAL[n]->name + "_" + GENERAL[n]->ROI[roi]->name;
  603. if (isLogImageSelect)
  604. {
  605. if (LogImageSelect.find(GENERAL[n]->ROI[roi]->name) != std::string::npos)
  606. LogImage(logPath, _imagename, NULL, &GENERAL[n]->ROI[roi]->result_klasse, time, GENERAL[n]->ROI[roi]->image_org);
  607. }
  608. else
  609. {
  610. LogImage(logPath, _imagename, NULL, &GENERAL[n]->ROI[roi]->result_klasse, time, GENERAL[n]->ROI[roi]->image_org);
  611. }
  612. }
  613. } break;
  614. case DoubleHyprid10:
  615. {
  616. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CNN Type: DoubleHyprid10");
  617. int _num, _numplus, _numminus;
  618. float _val, _valplus, _valminus;
  619. float _fit;
  620. float _result_save_file;
  621. tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);
  622. tflite->Invoke();
  623. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "After Invoke");
  624. _num = tflite->GetOutClassification(0, 9);
  625. _numplus = (_num + 1) % 10;
  626. _numminus = (_num - 1 + 10) % 10;
  627. _val = tflite->GetOutputValue(_num);
  628. _valplus = tflite->GetOutputValue(_numplus);
  629. _valminus = tflite->GetOutputValue(_numminus);
  630. float result = _num;
  631. if (_valplus > _valminus)
  632. {
  633. result = result + _valplus / (_valplus + _val);
  634. _fit = _val + _valplus;
  635. }
  636. else
  637. {
  638. result = result - _valminus / (_val + _valminus);
  639. _fit = _val + _valminus;
  640. }
  641. if (result >= 10)
  642. result = result - 10;
  643. if (result < 0)
  644. result = result + 10;
  645. string zw = "_num (p, m): " + to_string(_num) + " " + to_string(_numplus) + " " + to_string(_numminus);
  646. zw = zw + " _val (p, m): " + to_string(_val) + " " + to_string(_valplus) + " " + to_string(_valminus);
  647. zw = zw + " result: " + to_string(result) + " _fit: " + to_string(_fit);
  648. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw);
  649. _result_save_file = result;
  650. if (_fit < CNNGoodThreshold)
  651. {
  652. GENERAL[n]->ROI[roi]->isReject = true;
  653. result = -1;
  654. _result_save_file+= 100; // In case fit is not sufficient, the result should still be saved with "-10x.y".
  655. string zw = "Value Rejected due to Threshold (Fit: " + to_string(_fit) + ", Threshold: " + to_string(CNNGoodThreshold) + ")";
  656. LogFile.WriteToFile(ESP_LOG_WARN, TAG, zw);
  657. }
  658. else
  659. {
  660. GENERAL[n]->ROI[roi]->isReject = false;
  661. }
  662. GENERAL[n]->ROI[roi]->result_float = result;
  663. ESP_LOGD(TAG, "Result General(Analog)%i: %f", roi, GENERAL[n]->ROI[roi]->result_float);
  664. if (isLogImage)
  665. {
  666. string _imagename = GENERAL[n]->name + "_" + GENERAL[n]->ROI[roi]->name;
  667. if (isLogImageSelect)
  668. {
  669. if (LogImageSelect.find(GENERAL[n]->ROI[roi]->name) != std::string::npos)
  670. LogImage(logPath, _imagename, &_result_save_file, NULL, time, GENERAL[n]->ROI[roi]->image_org);
  671. }
  672. else
  673. {
  674. LogImage(logPath, _imagename, &_result_save_file, NULL, time, GENERAL[n]->ROI[roi]->image_org);
  675. }
  676. }
  677. }
  678. break;
  679. case Digital100:
  680. case Analogue100:
  681. {
  682. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CNN Type: Digital100 or Analogue100");
  683. int _num;
  684. float _result_save_file;
  685. tflite->LoadInputImageBasis(GENERAL[n]->ROI[roi]->image);
  686. tflite->Invoke();
  687. _num = tflite->GetOutClassification();
  688. if(GENERAL[n]->ROI[roi]->CCW)
  689. GENERAL[n]->ROI[roi]->result_float = 10 - ((float)_num / 10.0);
  690. else
  691. GENERAL[n]->ROI[roi]->result_float = (float)_num / 10.0;
  692. _result_save_file = GENERAL[n]->ROI[roi]->result_float;
  693. GENERAL[n]->ROI[roi]->isReject = false;
  694. ESP_LOGD(TAG, "Result General(Analog)%i - CCW: %d - %f", roi, GENERAL[n]->ROI[roi]->CCW, GENERAL[n]->ROI[roi]->result_float);
  695. if (isLogImage)
  696. {
  697. string _imagename = GENERAL[n]->name + "_" + GENERAL[n]->ROI[roi]->name;
  698. if (isLogImageSelect)
  699. {
  700. if (LogImageSelect.find(GENERAL[n]->ROI[roi]->name) != std::string::npos)
  701. LogImage(logPath, _imagename, &_result_save_file, NULL, time, GENERAL[n]->ROI[roi]->image_org);
  702. }
  703. else
  704. {
  705. LogImage(logPath, _imagename, &_result_save_file, NULL, time, GENERAL[n]->ROI[roi]->image_org);
  706. }
  707. }
  708. } break;
  709. default:
  710. break;
  711. }
  712. }
  713. }
  714. delete tflite;
  715. return true;
  716. }
  717. bool ClassFlowCNNGeneral::isExtendedResolution(int _number)
  718. {
  719. if (CNNType == Digital)
  720. return false;
  721. return true;
  722. }
  723. std::vector<HTMLInfo*> ClassFlowCNNGeneral::GetHTMLInfo()
  724. {
  725. std::vector<HTMLInfo*> result;
  726. for (int _ana = 0; _ana < GENERAL.size(); ++_ana)
  727. for (int i = 0; i < GENERAL[_ana]->ROI.size(); ++i)
  728. {
  729. ESP_LOGD(TAG, "Image: %d", (int) GENERAL[_ana]->ROI[i]->image);
  730. if (GENERAL[_ana]->ROI[i]->image)
  731. {
  732. if (GENERAL[_ana]->name == "default")
  733. GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
  734. else
  735. GENERAL[_ana]->ROI[i]->image->SaveToFile(FormatFileName("/sdcard/img_tmp/" + GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg"));
  736. }
  737. HTMLInfo *zw = new HTMLInfo;
  738. if (GENERAL[_ana]->name == "default")
  739. {
  740. zw->filename = GENERAL[_ana]->ROI[i]->name + ".jpg";
  741. zw->filename_org = GENERAL[_ana]->ROI[i]->name + ".jpg";
  742. }
  743. else
  744. {
  745. zw->filename = GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg";
  746. zw->filename_org = GENERAL[_ana]->name + "_" + GENERAL[_ana]->ROI[i]->name + ".jpg";
  747. }
  748. if (CNNType == Digital)
  749. zw->val = GENERAL[_ana]->ROI[i]->result_klasse;
  750. else
  751. zw->val = GENERAL[_ana]->ROI[i]->result_float;
  752. zw->image = GENERAL[_ana]->ROI[i]->image;
  753. zw->image_org = GENERAL[_ana]->ROI[i]->image_org;
  754. result.push_back(zw);
  755. }
  756. return result;
  757. }
  758. int ClassFlowCNNGeneral::getNumberGENERAL()
  759. {
  760. return GENERAL.size();
  761. }
  762. string ClassFlowCNNGeneral::getNameGENERAL(int _analog)
  763. {
  764. if (_analog < GENERAL.size())
  765. return GENERAL[_analog]->name;
  766. return "GENERAL DOES NOT EXIST";
  767. }
  768. general* ClassFlowCNNGeneral::GetGENERAL(int _analog)
  769. {
  770. if (_analog < GENERAL.size())
  771. return GENERAL[_analog];
  772. return NULL;
  773. }
  774. void ClassFlowCNNGeneral::UpdateNameNumbers(std::vector<std::string> *_name_numbers)
  775. {
  776. for (int _dig = 0; _dig < GENERAL.size(); _dig++)
  777. {
  778. std::string _name = GENERAL[_dig]->name;
  779. bool found = false;
  780. for (int i = 0; i < (*_name_numbers).size(); ++i)
  781. {
  782. if ((*_name_numbers)[i] == _name)
  783. found = true;
  784. }
  785. if (!found)
  786. (*_name_numbers).push_back(_name);
  787. }
  788. }
  789. string ClassFlowCNNGeneral::getReadoutRawString(int _analog)
  790. {
  791. string rt = "";
  792. if (_analog >= GENERAL.size() || GENERAL[_analog]==NULL || GENERAL[_analog]->ROI.size() == 0)
  793. return rt;
  794. for (int i = 0; i < GENERAL[_analog]->ROI.size(); ++i)
  795. {
  796. if (CNNType == Analogue || CNNType == Analogue100)
  797. {
  798. rt = rt + "," + RundeOutput(GENERAL[_analog]->ROI[i]->result_float, 1);
  799. }
  800. if (CNNType == Digital)
  801. {
  802. if (GENERAL[_analog]->ROI[i]->result_klasse == 10)
  803. rt = rt + ",N";
  804. else
  805. rt = rt + "," + RundeOutput(GENERAL[_analog]->ROI[i]->result_klasse, 0);
  806. }
  807. if ((CNNType == DoubleHyprid10) || (CNNType == Digital100))
  808. {
  809. rt = rt + "," + RundeOutput(GENERAL[_analog]->ROI[i]->result_float, 1);
  810. }
  811. }
  812. return rt;
  813. }