ClassFlowAlignment.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. #include "ClassFlowAlignment.h"
  2. #include "ClassFlowTakeImage.h"
  3. #include "ClassFlow.h"
  4. #include "MainFlowControl.h"
  5. #include "CRotateImage.h"
  6. #include "esp_log.h"
  7. #include "ClassLogFile.h"
  8. #include "psram.h"
  9. #include "../../include/defines.h"
  10. #include <new>
  11. #include <cstring>
  12. static const char *TAG = "ALIGN";
  13. // #define DEBUG_DETAIL_ON
  14. void ClassFlowAlignment::SetInitialParameter(void)
  15. {
  16. initialrotate = 0;
  17. anz_ref = 0;
  18. use_antialiasing = false;
  19. initialflip = false;
  20. SaveAllFiles = false;
  21. namerawimage = "/sdcard/img_tmp/raw.jpg";
  22. FileStoreRefAlignment = "/sdcard/config/align.txt";
  23. ListFlowControll = NULL;
  24. AlignAndCutImage = NULL;
  25. ImageBasis = NULL;
  26. ownsImageBasis = false;
  27. ImageTMP = NULL;
  28. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  29. AlgROIMutex = xSemaphoreCreateMutex();
  30. AlgROI = new (std::nothrow) ImageData;
  31. if (AlgROIMutex == NULL) {
  32. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to create AlgROI publication mutex");
  33. }
  34. #endif
  35. previousElement = NULL;
  36. disabled = false;
  37. SAD_criteria = 0.05;
  38. }
  39. ClassFlowAlignment::ClassFlowAlignment(std::vector<ClassFlow *> *lfc)
  40. {
  41. SetInitialParameter();
  42. ListFlowControll = lfc;
  43. for (int i = 0; i < ListFlowControll->size(); ++i) {
  44. if (((*ListFlowControll)[i])->name().compare("ClassFlowTakeImage") == 0) {
  45. ImageBasis = ((ClassFlowTakeImage *)(*ListFlowControll)[i])->rawImage;
  46. }
  47. }
  48. // the function take pictures does not exist --> must be created first ONLY FOR TEST PURPOSES
  49. if (!ImageBasis) {
  50. ESP_LOGD(TAG, "CImageBasis had to be created");
  51. ImageBasis = new (std::nothrow) CImageBasis("ImageBasis", namerawimage);
  52. ownsImageBasis = (ImageBasis != NULL);
  53. if (ImageBasis != NULL && !ImageBasis->ImageOkay()) { delete ImageBasis; ImageBasis = NULL; ownsImageBasis = false; }
  54. }
  55. }
  56. ClassFlowAlignment::~ClassFlowAlignment()
  57. {
  58. delete AlignAndCutImage;
  59. AlignAndCutImage = NULL;
  60. delete ImageTMP;
  61. ImageTMP = NULL;
  62. if (ownsImageBasis) {
  63. delete ImageBasis;
  64. ImageBasis = NULL;
  65. ownsImageBasis = false;
  66. }
  67. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  68. if (AlgROIMutex != NULL) {
  69. (void)xSemaphoreTake(AlgROIMutex, portMAX_DELAY);
  70. delete AlgROI;
  71. AlgROI = NULL;
  72. (void)xSemaphoreGive(AlgROIMutex);
  73. vSemaphoreDelete(AlgROIMutex);
  74. AlgROIMutex = NULL;
  75. } else {
  76. delete AlgROI;
  77. AlgROI = NULL;
  78. }
  79. #endif
  80. }
  81. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  82. bool ClassFlowAlignment::PublishAlgROI(const ImageData *image)
  83. {
  84. if (image == NULL || image->size == 0 || image->size > MAX_JPG_SIZE ||
  85. AlgROIMutex == NULL) return false;
  86. if (xSemaphoreTake(AlgROIMutex, portMAX_DELAY) != pdTRUE) return false;
  87. if (AlgROI == NULL) AlgROI = new (std::nothrow) ImageData;
  88. if (AlgROI == NULL) {
  89. (void)xSemaphoreGive(AlgROIMutex);
  90. return false;
  91. }
  92. // Keep the last complete JPEG visible until the replacement is fully copied.
  93. std::memcpy(AlgROI->data, image->data, image->size);
  94. AlgROI->size = image->size;
  95. (void)xSemaphoreGive(AlgROIMutex);
  96. return true;
  97. }
  98. esp_err_t ClassFlowAlignment::SendAlgROIToHTTP(httpd_req_t *req)
  99. {
  100. if (req == NULL || AlgROIMutex == NULL) return ESP_ERR_INVALID_ARG;
  101. if (xSemaphoreTake(AlgROIMutex, pdMS_TO_TICKS(250)) != pdTRUE) {
  102. return ESP_ERR_TIMEOUT;
  103. }
  104. if (AlgROI == NULL || AlgROI->size == 0 || AlgROI->size > MAX_JPG_SIZE) {
  105. (void)xSemaphoreGive(AlgROIMutex);
  106. return ESP_ERR_NOT_FOUND;
  107. }
  108. esp_err_t result = httpd_resp_set_type(req, "image/jpeg");
  109. if (result == ESP_OK) {
  110. result = httpd_resp_send(req, (const char *)AlgROI->data, AlgROI->size);
  111. }
  112. (void)xSemaphoreGive(AlgROIMutex);
  113. return result;
  114. }
  115. ImageData *ClassFlowAlignment::GetAlgROICopy(void)
  116. {
  117. if (AlgROIMutex == NULL) return NULL;
  118. ImageData *copy = new (std::nothrow) ImageData;
  119. if (copy == NULL) return NULL;
  120. if (xSemaphoreTake(AlgROIMutex, pdMS_TO_TICKS(1000)) != pdTRUE) {
  121. delete copy;
  122. return NULL;
  123. }
  124. if (AlgROI == NULL || AlgROI->size == 0 || AlgROI->size > MAX_JPG_SIZE) {
  125. (void)xSemaphoreGive(AlgROIMutex);
  126. delete copy;
  127. return NULL;
  128. }
  129. std::memcpy(copy->data, AlgROI->data, AlgROI->size);
  130. copy->size = AlgROI->size;
  131. (void)xSemaphoreGive(AlgROIMutex);
  132. return copy;
  133. }
  134. #endif
  135. bool ClassFlowAlignment::ReadParameter(FILE *pfile, string &aktparamgraph)
  136. {
  137. std::vector<string> splitted;
  138. int suchex = 40;
  139. int suchey = 40;
  140. int alg_algo = 0; // default=0; 1 =HIGHACCURACY; 2= FAST; 3= OFF //add disable aligment algo |01.2023
  141. aktparamgraph = trim(aktparamgraph);
  142. if (aktparamgraph.size() == 0)
  143. {
  144. if (!this->GetNextParagraph(pfile, aktparamgraph)) {
  145. return false;
  146. }
  147. }
  148. if (aktparamgraph.compare("[Alignment]") != 0)
  149. {
  150. // Paragraph does not fit Alignment
  151. return false;
  152. }
  153. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  154. {
  155. splitted = ZerlegeZeile(aktparamgraph);
  156. if ((toUpper(splitted[0]) == "FLIPIMAGESIZE") && (splitted.size() > 1)) {
  157. initialflip = alphanumericToBoolean(splitted[1]);
  158. }
  159. else if (((toUpper(splitted[0]) == "initialrotate") || (toUpper(splitted[0]) == "INITIALROTATE")) && (splitted.size() > 1)) {
  160. if (isStringNumeric(splitted[1])) {
  161. this->initialrotate = std::stod(splitted[1]);
  162. }
  163. }
  164. else if ((toUpper(splitted[0]) == "SEARCHFIELDX") && (splitted.size() > 1)) {
  165. if (isStringNumeric(splitted[1])) {
  166. suchex = std::stod(splitted[1]);
  167. }
  168. }
  169. else if ((toUpper(splitted[0]) == "SEARCHFIELDY") && (splitted.size() > 1)) {
  170. if (isStringNumeric(splitted[1])) {
  171. suchey = std::stod(splitted[1]);
  172. }
  173. }
  174. else if ((toUpper(splitted[0]) == "ANTIALIASING") && (splitted.size() > 1)) {
  175. use_antialiasing = alphanumericToBoolean(splitted[1]);
  176. }
  177. else if ((splitted.size() == 3) && (anz_ref < 2)) {
  178. if ((isStringNumeric(splitted[1])) && (isStringNumeric(splitted[2])))
  179. {
  180. References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
  181. References[anz_ref].target_x = std::stod(splitted[1]);
  182. References[anz_ref].target_y = std::stod(splitted[2]);
  183. anz_ref++;
  184. }
  185. else
  186. {
  187. References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
  188. References[anz_ref].target_x = 10;
  189. References[anz_ref].target_y = 10;
  190. anz_ref++;
  191. }
  192. }
  193. else if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1)) {
  194. SaveAllFiles = alphanumericToBoolean(splitted[1]);
  195. }
  196. else if ((toUpper(splitted[0]) == "ALIGNMENTALGO") && (splitted.size() > 1)) {
  197. #ifdef DEBUG_DETAIL_ON
  198. std::string zw2 = "Alignment mode selected: " + splitted[1];
  199. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
  200. #endif
  201. if (toUpper(splitted[1]) == "HIGHACCURACY") {
  202. alg_algo = 1;
  203. }
  204. if (toUpper(splitted[1]) == "FAST") {
  205. alg_algo = 2;
  206. }
  207. if (toUpper(splitted[1]) == "OFF") {
  208. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  209. alg_algo = 3;
  210. }
  211. }
  212. }
  213. for (int i = 0; i < anz_ref; ++i) {
  214. References[i].search_x = suchex;
  215. References[i].search_y = suchey;
  216. References[i].fastalg_SAD_criteria = SAD_criteria;
  217. References[i].alignment_algo = alg_algo;
  218. #ifdef DEBUG_DETAIL_ON
  219. std::string zw2 = "Alignment mode written: " + std::to_string(alg_algo);
  220. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
  221. #endif
  222. }
  223. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  224. if (References[0].alignment_algo != 3) {
  225. return LoadReferenceAlignmentValues();
  226. }
  227. return true;
  228. }
  229. string ClassFlowAlignment::getHTMLSingleStep(string host)
  230. {
  231. string result;
  232. result = "<p>Rotated Image: </p> <p><img src=\"" + host + "/img_tmp/rot.jpg\"></p>\n";
  233. result = result + "<p>Found Alignment: </p> <p><img src=\"" + host + "/img_tmp/rot_roi.jpg\"></p>\n";
  234. result = result + "<p>Aligned Image: </p> <p><img src=\"" + host + "/img_tmp/alg.jpg\"></p>\n";
  235. return result;
  236. }
  237. bool ClassFlowAlignment::doFlow(string time)
  238. {
  239. if (ImageBasis == NULL || !ImageBasis->ImageOkay()) {
  240. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Alignment has no valid source image");
  241. return false;
  242. }
  243. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  244. // Encode into a private temporary buffer, then publish the complete JPEG.
  245. // HTTP readers never observe a buffer while the encoder is modifying it.
  246. ImageData *initialPreview = ImageBasis->writeToMemoryAsJPG(90);
  247. if (initialPreview != NULL) {
  248. if (!PublishAlgROI(initialPreview)) {
  249. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to publish initial ROI preview");
  250. }
  251. delete initialPreview;
  252. } else {
  253. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to create initial ROI preview");
  254. LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
  255. }
  256. #endif
  257. if (ImageTMP == NULL) {
  258. ImageTMP = new (std::nothrow) CImageBasis("tmpImage", ImageBasis);
  259. if (ImageTMP == NULL || !ImageTMP->ImageOkay()) {
  260. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tmpImage -> Exec this round aborted!");
  261. LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
  262. delete ImageTMP;
  263. ImageTMP = NULL;
  264. return false;
  265. }
  266. }
  267. delete AlignAndCutImage;
  268. AlignAndCutImage = new (std::nothrow) CAlignAndCutImage("AlignAndCutImage", ImageBasis, ImageTMP);
  269. if (AlignAndCutImage == NULL) {
  270. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlignAndCutImage -> Exec this round aborted!");
  271. LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
  272. delete ImageTMP;
  273. ImageTMP = NULL;
  274. return false;
  275. }
  276. CRotateImage rt("rawImage", AlignAndCutImage, ImageTMP, initialflip);
  277. if (initialflip) {
  278. uint8_t* sourceImage = ImageBasis->RGBImageLock();
  279. if (sourceImage == NULL) {
  280. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to lock source image for initial flip");
  281. delete AlignAndCutImage;
  282. AlignAndCutImage = NULL;
  283. delete ImageTMP;
  284. ImageTMP = NULL;
  285. return false;
  286. }
  287. uint8_t* temporaryImage = ImageTMP->RGBImageLock();
  288. if (temporaryImage == NULL) {
  289. ImageBasis->RGBImageRelease();
  290. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to lock temporary image for initial flip");
  291. delete AlignAndCutImage;
  292. AlignAndCutImage = NULL;
  293. delete ImageTMP;
  294. ImageTMP = NULL;
  295. return false;
  296. }
  297. int _zw = ImageBasis->height;
  298. ImageBasis->height = ImageBasis->width;
  299. ImageBasis->width = _zw;
  300. _zw = ImageTMP->width;
  301. ImageTMP->width = ImageTMP->height;
  302. ImageTMP->height = _zw;
  303. ImageTMP->RGBImageRelease();
  304. ImageBasis->RGBImageRelease();
  305. }
  306. if ((initialrotate != 0) || initialflip) {
  307. if (use_antialiasing) {
  308. rt.RotateAntiAliasing(initialrotate);
  309. }
  310. else {
  311. rt.Rotate(initialrotate);
  312. }
  313. if (SaveAllFiles) {
  314. AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/rot.jpg"));
  315. }
  316. }
  317. // no align algo if set to 3 = off //add disable aligment algo |01.2023
  318. if (References[0].alignment_algo != 3) {
  319. if (!AlignAndCutImage->Align(&References[0], &References[1])) {
  320. SaveReferenceAlignmentValues();
  321. }
  322. } // no align
  323. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  324. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  325. if (References[0].alignment_algo != 3) {
  326. DrawRef(ImageTMP);
  327. }
  328. flowctrl.DigitDrawROI(ImageTMP);
  329. flowctrl.AnalogDrawROI(ImageTMP);
  330. ImageData *alignedPreview = ImageTMP->writeToMemoryAsJPG(90);
  331. if (alignedPreview != NULL) {
  332. if (!PublishAlgROI(alignedPreview)) {
  333. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to publish aligned ROI preview");
  334. }
  335. delete alignedPreview;
  336. } else {
  337. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to create aligned ROI preview");
  338. }
  339. #endif
  340. if (SaveAllFiles) {
  341. AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/alg.jpg"));
  342. ImageTMP->SaveToFile(FormatFileName("/sdcard/img_tmp/alg_roi.jpg"));
  343. }
  344. // must be deleted to have memory space for loading tflite
  345. delete ImageTMP;
  346. ImageTMP = NULL;
  347. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  348. if (References[0].alignment_algo != 3) {
  349. return LoadReferenceAlignmentValues();
  350. }
  351. return true;
  352. }
  353. void ClassFlowAlignment::SaveReferenceAlignmentValues()
  354. {
  355. FILE *pFile;
  356. std::string zwtime, zwvalue;
  357. pFile = fopen(FileStoreRefAlignment.c_str(), "w");
  358. if (pFile == NULL) {
  359. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SaveReferenceAlignmentValues: Failed to open " + FileStoreRefAlignment);
  360. return;
  361. }
  362. if (strlen(zwtime.c_str()) == 0) {
  363. time_t rawtime;
  364. struct tm *timeinfo;
  365. char buffer[80];
  366. time(&rawtime);
  367. timeinfo = localtime(&rawtime);
  368. strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S", timeinfo);
  369. zwtime = std::string(buffer);
  370. }
  371. fputs(zwtime.c_str(), pFile);
  372. fputs("\n", pFile);
  373. zwvalue = std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_y);
  374. zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
  375. zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
  376. fputs(zwvalue.c_str(), pFile);
  377. fputs("\n", pFile);
  378. zwvalue = std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_y);
  379. zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
  380. zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
  381. fputs(zwvalue.c_str(), pFile);
  382. fputs("\n", pFile);
  383. fclose(pFile);
  384. }
  385. bool ClassFlowAlignment::LoadReferenceAlignmentValues(void)
  386. {
  387. FILE *pFile;
  388. char zw[1024];
  389. string zwvalue;
  390. std::vector<string> splitted;
  391. pFile = fopen(FileStoreRefAlignment.c_str(), "r");
  392. if (pFile == NULL) {
  393. return false;
  394. }
  395. fgets(zw, 1024, pFile);
  396. ESP_LOGD(TAG, "%s", zw);
  397. fgets(zw, 1024, pFile);
  398. splitted = ZerlegeZeile(std::string(zw), " \t");
  399. if (splitted.size() < 6) {
  400. fclose(pFile);
  401. return false;
  402. }
  403. References[0].fastalg_x = stoi(splitted[0]);
  404. References[0].fastalg_y = stoi(splitted[1]);
  405. References[0].fastalg_SAD = stof(splitted[2]);
  406. References[0].fastalg_min = stoi(splitted[3]);
  407. References[0].fastalg_max = stoi(splitted[4]);
  408. References[0].fastalg_avg = stof(splitted[5]);
  409. fgets(zw, 1024, pFile);
  410. splitted = ZerlegeZeile(std::string(zw));
  411. if (splitted.size() < 6) {
  412. fclose(pFile);
  413. return false;
  414. }
  415. References[1].fastalg_x = stoi(splitted[0]);
  416. References[1].fastalg_y = stoi(splitted[1]);
  417. References[1].fastalg_SAD = stof(splitted[2]);
  418. References[1].fastalg_min = stoi(splitted[3]);
  419. References[1].fastalg_max = stoi(splitted[4]);
  420. References[1].fastalg_avg = stof(splitted[5]);
  421. fclose(pFile);
  422. /*#ifdef DEBUG_DETAIL_ON
  423. std::string _zw = "\tLoadReferences[0]\tx,y:\t" + std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_x);
  424. _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
  425. _zw = _zw + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
  426. LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
  427. _zw = "\tLoadReferences[1]\tx,y:\t" + std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_x);
  428. _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
  429. _zw = _zw + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
  430. LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
  431. #endif*/
  432. return true;
  433. }
  434. void ClassFlowAlignment::DrawRef(CImageBasis *_zw)
  435. {
  436. if (_zw->ImageOkay()) {
  437. _zw->drawRect(References[0].target_x, References[0].target_y, References[0].width, References[0].height, 255, 0, 0, 2);
  438. _zw->drawRect(References[1].target_x, References[1].target_y, References[1].width, References[1].height, 255, 0, 0, 2);
  439. }
  440. }