CFindTemplate.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #include "CFindTemplate.h"
  2. #include "ClassLogFile.h"
  3. #include "Helper.h"
  4. #include "../../include/defines.h"
  5. #include <esp_log.h>
  6. #include <esp_timer.h>
  7. #include "freertos/FreeRTOS.h"
  8. #include "freertos/task.h"
  9. #include <cstdint>
  10. static const char* TAG = "C FIND TEMPL";
  11. // #define DEBUG_DETAIL_ON
  12. bool CFindTemplate::FindTemplate(RefInfo *_ref)
  13. {
  14. uint8_t* rgb_template;
  15. if (file_size(_ref->image_file.c_str()) == 0) {
  16. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _ref->image_file + " is empty!");
  17. return false;
  18. }
  19. rgb_template = stbi_load(_ref->image_file.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
  20. if (rgb_template == NULL) {
  21. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to load " + _ref->image_file + "! Is it corrupted?");
  22. return false;
  23. }
  24. // ESP_LOGD(TAG, "FindTemplate 01");
  25. int ow, ow_start, ow_stop;
  26. int oh, oh_start, oh_stop;
  27. if (_ref->search_x == 0)
  28. {
  29. _ref->search_x = width;
  30. _ref->found_x = 0;
  31. }
  32. if (_ref->search_y == 0)
  33. {
  34. _ref->search_y = height;
  35. _ref->found_y = 0;
  36. }
  37. ow_start = _ref->target_x - _ref->search_x;
  38. ow_start = std::max(ow_start, 0);
  39. ow_stop = _ref->target_x + _ref->search_x;
  40. if ((ow_stop + tpl_width) > width)
  41. ow_stop = width - tpl_width;
  42. ow = ow_stop - ow_start + 1;
  43. oh_start = _ref->target_y - _ref->search_y;
  44. oh_start = std::max(oh_start, 0);
  45. oh_stop = _ref->target_y + _ref->search_y;
  46. if ((oh_stop + tpl_height) > height)
  47. oh_stop = height - tpl_height;
  48. oh = oh_stop - oh_start + 1;
  49. float avg = 0, SAD = 0;
  50. int min = 0, max = 0;
  51. bool isSimilar = false;
  52. // ESP_LOGD(TAG, "FindTemplate 02");
  53. if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1)) // für Testzwecke immer Berechnen
  54. {
  55. isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y, min, avg, max, SAD, _ref->fastalg_SAD, _ref->fastalg_SAD_criteria);
  56. /*#ifdef DEBUG_DETAIL_ON
  57. std::string zw = "\t" + _ref->image_file + "\tt1_x_y:\t" + std::to_string(_ref->fastalg_x) + "\t" + std::to_string(_ref->fastalg_y);
  58. zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(min) + "\t" + std::to_string(avg) + "\t" + std::to_string(max) + "\t"+ std::to_string(SAD);
  59. LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
  60. #endif*/
  61. }
  62. // ESP_LOGD(TAG, "FindTemplate 03");
  63. if (isSimilar)
  64. {
  65. #ifdef DEBUG_DETAIL_ON
  66. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment sucessfull");
  67. #endif
  68. _ref->found_x = _ref->fastalg_x;
  69. _ref->found_y = _ref->fastalg_y;
  70. stbi_image_free(rgb_template);
  71. return true;
  72. }
  73. // ESP_LOGD(TAG, "FindTemplate 04");
  74. // Sum of squared differences in integer arithmetic: the ESP32 FPU is single precision only,
  75. // so the former double/pow() version ran in software emulation and took several seconds per reference.
  76. // The result is identical: the sum is exact either way and the search order / tie-breaking is unchanged.
  77. uint64_t aktSAD;
  78. uint64_t minSAD = UINT64_MAX;
  79. RGBImageLock();
  80. // ESP_LOGD(TAG, "FindTemplate 05");
  81. int xouter, youter, tpl_x, tpl_y, _ch;
  82. int _anzchannels = channels;
  83. if (_ref->alignment_algo == 0) // 0 = "Default" (nur R-Kanal)
  84. _anzchannels = 1;
  85. // PSRAM-Zugriffe auf Core 0 verdrängen den WiFi-Stack. Spätestens alle 50 ms
  86. // den Core abgeben, damit Beacons weiter verarbeitet werden (Tick = 10 ms).
  87. int64_t nextYieldUs = esp_timer_get_time() + 50000;
  88. const int tpl_row_len = tpl_width * channels;
  89. for (xouter = ow_start; xouter <= ow_stop; xouter++)
  90. for (youter = oh_start; youter <= oh_stop; ++youter)
  91. {
  92. aktSAD = 0;
  93. // Walk the template row by row so that image accesses stay sequential in (PSRAM) memory
  94. for (tpl_y = 0; tpl_y < tpl_height; tpl_y++)
  95. {
  96. const stbi_uc* p_org = rgb_image + (channels * ((youter + tpl_y) * width + xouter));
  97. const stbi_uc* p_tpl = rgb_template + (tpl_y * tpl_row_len);
  98. uint32_t rowSAD = 0;
  99. for (tpl_x = 0; tpl_x < tpl_row_len; tpl_x += channels)
  100. {
  101. for (_ch = 0; _ch < _anzchannels; ++_ch)
  102. {
  103. int dif = p_tpl[tpl_x + _ch] - p_org[tpl_x + _ch];
  104. rowSAD += dif * dif;
  105. }
  106. }
  107. aktSAD += rowSAD;
  108. if (aktSAD >= minSAD) // can no longer become the new minimum
  109. break;
  110. }
  111. if (aktSAD < minSAD)
  112. {
  113. minSAD = aktSAD;
  114. _ref->found_x = xouter;
  115. _ref->found_y = youter;
  116. }
  117. if (esp_timer_get_time() >= nextYieldUs)
  118. {
  119. vTaskDelay(1);
  120. nextYieldUs = esp_timer_get_time() + 50000;
  121. }
  122. }
  123. // ESP_LOGD(TAG, "FindTemplate 06");
  124. if (_ref->alignment_algo == 2)
  125. CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y, min, avg, max, SAD, _ref->fastalg_SAD, _ref->fastalg_SAD_criteria);
  126. // ESP_LOGD(TAG, "FindTemplate 07");
  127. _ref->fastalg_x = _ref->found_x;
  128. _ref->fastalg_y = _ref->found_y;
  129. _ref->fastalg_min = min;
  130. _ref->fastalg_avg = avg;
  131. _ref->fastalg_max = max;
  132. _ref->fastalg_SAD = SAD;
  133. /*#ifdef DEBUG_DETAIL_ON
  134. std::string zw = "\t" + _ref->image_file + "\tt1_x_y:\t" + std::to_string(_ref->fastalg_x) + "\t" + std::to_string(_ref->fastalg_y);
  135. zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(min) + "\t" + std::to_string(avg) + "\t" + std::to_string(max) + "\t"+ std::to_string(SAD);
  136. LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
  137. #endif*/
  138. RGBImageRelease();
  139. stbi_image_free(rgb_template);
  140. // ESP_LOGD(TAG, "FindTemplate 08");
  141. return false;
  142. }
  143. // Compares the template with the image at (_startx, _starty) and reports whether the match is still as
  144. // good as the stored one. Used by the "Fast" alignment to skip the full search.
  145. bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _starty, int &min, float &avg, int &max, float &SAD, float _SADold, float _SADcrit)
  146. {
  147. int dif;
  148. int minDif = 255;
  149. int maxDif = -255;
  150. double avgDifSum = 0;
  151. long int anz = 0;
  152. double aktSAD = 0;
  153. int xouter, youter, _ch;
  154. // The template has to lie completely inside the image at this position. The stored position comes
  155. // from /config/align.txt and may belong to an older reference image.
  156. if ((_startx < 0) || (_starty < 0) || ((_startx + tpl_width) > width) || ((_starty + tpl_height) > height))
  157. return false;
  158. // Walk the template, not the search area: the former loop ran over the search area size (plus one)
  159. // and so read past the end of the template buffer and compared pixels that are not part of the marker.
  160. for (xouter = 0; xouter < tpl_width; xouter++)
  161. for (youter = 0; youter < tpl_height; ++youter)
  162. {
  163. stbi_uc* p_org = rgb_image + (channels * ((youter + _starty) * width + (xouter + _startx)));
  164. stbi_uc* p_tpl = _rgb_tmpl + (channels * (youter * tpl_width + xouter));
  165. for (_ch = 0; _ch < channels; ++_ch)
  166. {
  167. dif = (int)p_tpl[_ch] - (int)p_org[_ch];
  168. aktSAD += dif * dif;
  169. if (dif < minDif) minDif = dif;
  170. if (dif > maxDif) maxDif = dif;
  171. avgDifSum += dif;
  172. anz++;
  173. }
  174. }
  175. avg = avgDifSum / anz;
  176. min = minDif;
  177. max = maxDif;
  178. SAD = sqrt(aktSAD) / anz;
  179. float _SADdif = abs(SAD - _SADold);
  180. ESP_LOGD(TAG, "Anzahl %ld, avgDifSum %fd, avg %f, SAD_neu: %fd, _SAD_old: %f, _SAD_crit:%f", anz, avgDifSum, avg, SAD, _SADold, _SADdif);
  181. if (_SADdif <= _SADcrit)
  182. return true;
  183. return false;
  184. }