ClassFlowCNNGeneral.cpp 41 KB

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