ClassFlowAlignment.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. // Copy under the publication mutex, then release it before network I/O.
  102. // A slow browser must never stall the flow task publishing the next frame.
  103. ImageData *snapshot = new (std::nothrow) ImageData;
  104. if (snapshot == NULL) return ESP_ERR_NO_MEM;
  105. if (xSemaphoreTake(AlgROIMutex, pdMS_TO_TICKS(250)) != pdTRUE) {
  106. delete snapshot;
  107. return ESP_ERR_TIMEOUT;
  108. }
  109. if (AlgROI == NULL || AlgROI->size == 0 || AlgROI->size > MAX_JPG_SIZE) {
  110. (void)xSemaphoreGive(AlgROIMutex);
  111. delete snapshot;
  112. return ESP_ERR_NOT_FOUND;
  113. }
  114. std::memcpy(snapshot->data, AlgROI->data, AlgROI->size);
  115. snapshot->size = AlgROI->size;
  116. (void)xSemaphoreGive(AlgROIMutex);
  117. esp_err_t result = httpd_resp_set_type(req, "image/jpeg");
  118. if (result == ESP_OK) {
  119. result = httpd_resp_send(req, (const char *)snapshot->data, snapshot->size);
  120. }
  121. delete snapshot;
  122. return result;
  123. }
  124. ImageData *ClassFlowAlignment::GetAlgROICopy(void)
  125. {
  126. if (AlgROIMutex == NULL) return NULL;
  127. ImageData *copy = new (std::nothrow) ImageData;
  128. if (copy == NULL) return NULL;
  129. if (xSemaphoreTake(AlgROIMutex, pdMS_TO_TICKS(1000)) != pdTRUE) {
  130. delete copy;
  131. return NULL;
  132. }
  133. if (AlgROI == NULL || AlgROI->size == 0 || AlgROI->size > MAX_JPG_SIZE) {
  134. (void)xSemaphoreGive(AlgROIMutex);
  135. delete copy;
  136. return NULL;
  137. }
  138. std::memcpy(copy->data, AlgROI->data, AlgROI->size);
  139. copy->size = AlgROI->size;
  140. (void)xSemaphoreGive(AlgROIMutex);
  141. return copy;
  142. }
  143. #endif
  144. bool ClassFlowAlignment::ReadParameter(FILE *pfile, string &aktparamgraph)
  145. {
  146. std::vector<string> splitted;
  147. int suchex = 40;
  148. int suchey = 40;
  149. int alg_algo = 0; // default=0; 1 =HIGHACCURACY; 2= FAST; 3= OFF //add disable aligment algo |01.2023
  150. aktparamgraph = trim(aktparamgraph);
  151. if (aktparamgraph.size() == 0)
  152. {
  153. if (!this->GetNextParagraph(pfile, aktparamgraph)) {
  154. return false;
  155. }
  156. }
  157. if (aktparamgraph.compare("[Alignment]") != 0)
  158. {
  159. // Paragraph does not fit Alignment
  160. return false;
  161. }
  162. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  163. {
  164. splitted = ZerlegeZeile(aktparamgraph);
  165. if ((toUpper(splitted[0]) == "FLIPIMAGESIZE") && (splitted.size() > 1)) {
  166. initialflip = alphanumericToBoolean(splitted[1]);
  167. }
  168. else if (((toUpper(splitted[0]) == "initialrotate") || (toUpper(splitted[0]) == "INITIALROTATE")) && (splitted.size() > 1)) {
  169. if (isStringNumeric(splitted[1])) {
  170. this->initialrotate = std::stod(splitted[1]);
  171. }
  172. }
  173. else if ((toUpper(splitted[0]) == "SEARCHFIELDX") && (splitted.size() > 1)) {
  174. if (isStringNumeric(splitted[1])) {
  175. suchex = std::stod(splitted[1]);
  176. }
  177. }
  178. else if ((toUpper(splitted[0]) == "SEARCHFIELDY") && (splitted.size() > 1)) {
  179. if (isStringNumeric(splitted[1])) {
  180. suchey = std::stod(splitted[1]);
  181. }
  182. }
  183. else if ((toUpper(splitted[0]) == "ANTIALIASING") && (splitted.size() > 1)) {
  184. use_antialiasing = alphanumericToBoolean(splitted[1]);
  185. }
  186. else if ((splitted.size() == 3) && (anz_ref < 2)) {
  187. if ((isStringNumeric(splitted[1])) && (isStringNumeric(splitted[2])))
  188. {
  189. References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
  190. References[anz_ref].target_x = std::stod(splitted[1]);
  191. References[anz_ref].target_y = std::stod(splitted[2]);
  192. anz_ref++;
  193. }
  194. else
  195. {
  196. References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
  197. References[anz_ref].target_x = 10;
  198. References[anz_ref].target_y = 10;
  199. anz_ref++;
  200. }
  201. }
  202. else if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1)) {
  203. SaveAllFiles = alphanumericToBoolean(splitted[1]);
  204. }
  205. else if ((toUpper(splitted[0]) == "ALIGNMENTALGO") && (splitted.size() > 1)) {
  206. #ifdef DEBUG_DETAIL_ON
  207. std::string zw2 = "Alignment mode selected: " + splitted[1];
  208. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
  209. #endif
  210. if (toUpper(splitted[1]) == "HIGHACCURACY") {
  211. alg_algo = 1;
  212. }
  213. if (toUpper(splitted[1]) == "FAST") {
  214. alg_algo = 2;
  215. }
  216. if (toUpper(splitted[1]) == "OFF") {
  217. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  218. alg_algo = 3;
  219. }
  220. }
  221. }
  222. for (int i = 0; i < anz_ref; ++i) {
  223. References[i].search_x = suchex;
  224. References[i].search_y = suchey;
  225. References[i].fastalg_SAD_criteria = SAD_criteria;
  226. References[i].alignment_algo = alg_algo;
  227. #ifdef DEBUG_DETAIL_ON
  228. std::string zw2 = "Alignment mode written: " + std::to_string(alg_algo);
  229. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
  230. #endif
  231. }
  232. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  233. if (References[0].alignment_algo != 3) {
  234. return LoadReferenceAlignmentValues();
  235. }
  236. return true;
  237. }
  238. string ClassFlowAlignment::getHTMLSingleStep(string host)
  239. {
  240. string result;
  241. result = "<p>Rotated Image: </p> <p><img src=\"" + host + "/img_tmp/rot.jpg\"></p>\n";
  242. result = result + "<p>Found Alignment: </p> <p><img src=\"" + host + "/img_tmp/rot_roi.jpg\"></p>\n";
  243. result = result + "<p>Aligned Image: </p> <p><img src=\"" + host + "/img_tmp/alg.jpg\"></p>\n";
  244. return result;
  245. }
  246. bool ClassFlowAlignment::doFlow(string time)
  247. {
  248. if (ImageBasis == NULL || !ImageBasis->ImageOkay()) {
  249. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Alignment has no valid source image");
  250. return false;
  251. }
  252. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  253. // Encode into a private temporary buffer, then publish the complete JPEG.
  254. // HTTP readers never observe a buffer while the encoder is modifying it.
  255. ImageData *initialPreview = ImageBasis->writeToMemoryAsJPG(90);
  256. if (initialPreview != NULL) {
  257. if (!PublishAlgROI(initialPreview)) {
  258. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to publish initial ROI preview");
  259. }
  260. delete initialPreview;
  261. } else {
  262. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to create initial ROI preview");
  263. LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
  264. }
  265. #endif
  266. if (ImageTMP == NULL) {
  267. ImageTMP = new (std::nothrow) CImageBasis("tmpImage", ImageBasis);
  268. if (ImageTMP == NULL || !ImageTMP->ImageOkay()) {
  269. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tmpImage -> Exec this round aborted!");
  270. LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
  271. delete ImageTMP;
  272. ImageTMP = NULL;
  273. return false;
  274. }
  275. }
  276. delete AlignAndCutImage;
  277. AlignAndCutImage = new (std::nothrow) CAlignAndCutImage("AlignAndCutImage", ImageBasis, ImageTMP);
  278. if (AlignAndCutImage == NULL) {
  279. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlignAndCutImage -> Exec this round aborted!");
  280. LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
  281. delete ImageTMP;
  282. ImageTMP = NULL;
  283. return false;
  284. }
  285. CRotateImage rt("rawImage", AlignAndCutImage, ImageTMP, initialflip);
  286. if (initialflip) {
  287. uint8_t* sourceImage = ImageBasis->RGBImageLock();
  288. if (sourceImage == NULL) {
  289. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to lock source image for initial flip");
  290. delete AlignAndCutImage;
  291. AlignAndCutImage = NULL;
  292. delete ImageTMP;
  293. ImageTMP = NULL;
  294. return false;
  295. }
  296. uint8_t* temporaryImage = ImageTMP->RGBImageLock();
  297. if (temporaryImage == NULL) {
  298. ImageBasis->RGBImageRelease();
  299. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to lock temporary image for initial flip");
  300. delete AlignAndCutImage;
  301. AlignAndCutImage = NULL;
  302. delete ImageTMP;
  303. ImageTMP = NULL;
  304. return false;
  305. }
  306. int _zw = ImageBasis->height;
  307. ImageBasis->height = ImageBasis->width;
  308. ImageBasis->width = _zw;
  309. _zw = ImageTMP->width;
  310. ImageTMP->width = ImageTMP->height;
  311. ImageTMP->height = _zw;
  312. ImageTMP->RGBImageRelease();
  313. ImageBasis->RGBImageRelease();
  314. }
  315. if ((initialrotate != 0) || initialflip) {
  316. if (use_antialiasing) {
  317. rt.RotateAntiAliasing(initialrotate);
  318. }
  319. else {
  320. rt.Rotate(initialrotate);
  321. }
  322. if (SaveAllFiles) {
  323. AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/rot.jpg"));
  324. }
  325. }
  326. // no align algo if set to 3 = off //add disable aligment algo |01.2023
  327. if (References[0].alignment_algo != 3) {
  328. if (!AlignAndCutImage->Align(&References[0], &References[1])) {
  329. SaveReferenceAlignmentValues();
  330. }
  331. } // no align
  332. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  333. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  334. if (References[0].alignment_algo != 3) {
  335. DrawRef(ImageTMP);
  336. }
  337. flowctrl.DigitDrawROI(ImageTMP);
  338. flowctrl.AnalogDrawROI(ImageTMP);
  339. ImageData *alignedPreview = ImageTMP->writeToMemoryAsJPG(90);
  340. if (alignedPreview != NULL) {
  341. if (!PublishAlgROI(alignedPreview)) {
  342. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to publish aligned ROI preview");
  343. }
  344. delete alignedPreview;
  345. } else {
  346. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to create aligned ROI preview");
  347. }
  348. #endif
  349. if (SaveAllFiles) {
  350. AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/alg.jpg"));
  351. ImageTMP->SaveToFile(FormatFileName("/sdcard/img_tmp/alg_roi.jpg"));
  352. }
  353. // must be deleted to have memory space for loading tflite
  354. delete ImageTMP;
  355. ImageTMP = NULL;
  356. // no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
  357. if (References[0].alignment_algo != 3) {
  358. return LoadReferenceAlignmentValues();
  359. }
  360. return true;
  361. }
  362. void ClassFlowAlignment::SaveReferenceAlignmentValues()
  363. {
  364. FILE *pFile;
  365. std::string zwtime, zwvalue;
  366. pFile = fopen(FileStoreRefAlignment.c_str(), "w");
  367. if (pFile == NULL) {
  368. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SaveReferenceAlignmentValues: Failed to open " + FileStoreRefAlignment);
  369. return;
  370. }
  371. if (strlen(zwtime.c_str()) == 0) {
  372. time_t rawtime;
  373. struct tm *timeinfo;
  374. char buffer[80];
  375. time(&rawtime);
  376. timeinfo = localtime(&rawtime);
  377. strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S", timeinfo);
  378. zwtime = std::string(buffer);
  379. }
  380. fputs(zwtime.c_str(), pFile);
  381. fputs("\n", pFile);
  382. zwvalue = std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_y);
  383. zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
  384. zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
  385. fputs(zwvalue.c_str(), pFile);
  386. fputs("\n", pFile);
  387. zwvalue = std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_y);
  388. zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
  389. zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
  390. fputs(zwvalue.c_str(), pFile);
  391. fputs("\n", pFile);
  392. fclose(pFile);
  393. }
  394. bool ClassFlowAlignment::LoadReferenceAlignmentValues(void)
  395. {
  396. FILE *pFile;
  397. char zw[1024];
  398. string zwvalue;
  399. std::vector<string> splitted;
  400. pFile = fopen(FileStoreRefAlignment.c_str(), "r");
  401. if (pFile == NULL) {
  402. return false;
  403. }
  404. fgets(zw, 1024, pFile);
  405. ESP_LOGD(TAG, "%s", zw);
  406. fgets(zw, 1024, pFile);
  407. splitted = ZerlegeZeile(std::string(zw), " \t");
  408. if (splitted.size() < 6) {
  409. fclose(pFile);
  410. return false;
  411. }
  412. References[0].fastalg_x = stoi(splitted[0]);
  413. References[0].fastalg_y = stoi(splitted[1]);
  414. References[0].fastalg_SAD = stof(splitted[2]);
  415. References[0].fastalg_min = stoi(splitted[3]);
  416. References[0].fastalg_max = stoi(splitted[4]);
  417. References[0].fastalg_avg = stof(splitted[5]);
  418. fgets(zw, 1024, pFile);
  419. splitted = ZerlegeZeile(std::string(zw));
  420. if (splitted.size() < 6) {
  421. fclose(pFile);
  422. return false;
  423. }
  424. References[1].fastalg_x = stoi(splitted[0]);
  425. References[1].fastalg_y = stoi(splitted[1]);
  426. References[1].fastalg_SAD = stof(splitted[2]);
  427. References[1].fastalg_min = stoi(splitted[3]);
  428. References[1].fastalg_max = stoi(splitted[4]);
  429. References[1].fastalg_avg = stof(splitted[5]);
  430. fclose(pFile);
  431. /*#ifdef DEBUG_DETAIL_ON
  432. std::string _zw = "\tLoadReferences[0]\tx,y:\t" + std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_x);
  433. _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
  434. _zw = _zw + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
  435. LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
  436. _zw = "\tLoadReferences[1]\tx,y:\t" + std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_x);
  437. _zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
  438. _zw = _zw + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
  439. LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
  440. #endif*/
  441. return true;
  442. }
  443. void ClassFlowAlignment::DrawRef(CImageBasis *_zw)
  444. {
  445. if (_zw->ImageOkay()) {
  446. _zw->drawRect(References[0].target_x, References[0].target_y, References[0].width, References[0].height, 255, 0, 0, 2);
  447. _zw->drawRect(References[1].target_x, References[1].target_y, References[1].width, References[1].height, 255, 0, 0, 2);
  448. }
  449. }