CFindTemplate.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. #include <limits.h>
  11. static const char* TAG = "C FIND TEMPL";
  12. static bool getTemplateBufferSize(int width, int height, int channels, size_t* size)
  13. {
  14. if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
  15. const size_t w = static_cast<size_t>(width);
  16. const size_t h = static_cast<size_t>(height);
  17. const size_t c = static_cast<size_t>(channels);
  18. if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
  19. const size_t total = w * h * c;
  20. if (total > static_cast<size_t>(INT_MAX)) return false;
  21. *size = total;
  22. return true;
  23. }
  24. // #define DEBUG_DETAIL_ON
  25. bool CFindTemplate::FindTemplate(RefInfo *_ref, bool sourceIsStableSnapshot)
  26. {
  27. if (_ref == NULL || rgb_image == NULL || width <= 0 || height <= 0 || channels <= 0) {
  28. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image or reference is unavailable");
  29. return false;
  30. }
  31. if (file_size(_ref->image_file.c_str()) == 0) {
  32. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _ref->image_file + " is empty!");
  33. return false;
  34. }
  35. uint8_t* rgb_template = stbi_load(_ref->image_file.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
  36. if (rgb_template == NULL) {
  37. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to load " + _ref->image_file + "! Is it corrupted?");
  38. return false;
  39. }
  40. size_t templateBytes = 0;
  41. if (!getTemplateBufferSize(tpl_width, tpl_height, channels, &templateBytes) ||
  42. tpl_width > width || tpl_height > height) {
  43. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: template dimensions are invalid or exceed source image");
  44. stbi_image_free(rgb_template);
  45. return false;
  46. }
  47. // Alignment passes an immutable copy in the shared tmpImage workspace.
  48. // Searching that snapshot must not hold the global image mutex for seconds.
  49. uint8_t* source = rgb_image;
  50. const bool sourceLocked = !sourceIsStableSnapshot;
  51. if (sourceLocked) {
  52. source = RGBImageLock();
  53. if (source == NULL) {
  54. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image is locked");
  55. stbi_image_free(rgb_template);
  56. return false;
  57. }
  58. }
  59. if (_ref->search_x == 0) {
  60. _ref->search_x = width;
  61. _ref->found_x = 0;
  62. }
  63. if (_ref->search_y == 0) {
  64. _ref->search_y = height;
  65. _ref->found_y = 0;
  66. }
  67. const int64_t leftCandidate = static_cast<int64_t>(_ref->target_x) - _ref->search_x;
  68. const int64_t rightCandidate = static_cast<int64_t>(_ref->target_x) + _ref->search_x;
  69. const int64_t topCandidate = static_cast<int64_t>(_ref->target_y) - _ref->search_y;
  70. const int64_t bottomCandidate = static_cast<int64_t>(_ref->target_y) + _ref->search_y;
  71. const int ow_start = static_cast<int>(std::max<int64_t>(0, leftCandidate));
  72. const int ow_stop = static_cast<int>(std::min<int64_t>(rightCandidate, width - tpl_width));
  73. const int oh_start = static_cast<int>(std::max<int64_t>(0, topCandidate));
  74. const int oh_stop = static_cast<int>(std::min<int64_t>(bottomCandidate, height - tpl_height));
  75. if (ow_stop < ow_start || oh_stop < oh_start) {
  76. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: search window does not intersect source image");
  77. if (sourceLocked) RGBImageRelease();
  78. stbi_image_free(rgb_template);
  79. return false;
  80. }
  81. float avg = 0, SAD = 0;
  82. int min = 0, max = 0;
  83. bool isSimilar = false;
  84. if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1)) {
  85. isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y,
  86. min, avg, max, SAD, _ref->fastalg_SAD,
  87. _ref->fastalg_SAD_criteria);
  88. }
  89. if (isSimilar) {
  90. #ifdef DEBUG_DETAIL_ON
  91. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment successful");
  92. #endif
  93. _ref->found_x = _ref->fastalg_x;
  94. _ref->found_y = _ref->fastalg_y;
  95. if (sourceLocked) RGBImageRelease();
  96. stbi_image_free(rgb_template);
  97. return true;
  98. }
  99. uint64_t aktSAD;
  100. uint64_t minSAD = UINT64_MAX;
  101. const int anzChannels = (_ref->alignment_algo == 0) ? 1 : channels;
  102. const size_t templateRowLength = static_cast<size_t>(tpl_width) * static_cast<size_t>(channels);
  103. int64_t nextYieldUs = esp_timer_get_time() + 50000;
  104. for (int xouter = ow_start; xouter <= ow_stop; ++xouter) {
  105. for (int youter = oh_start; youter <= oh_stop; ++youter) {
  106. aktSAD = 0;
  107. for (int tpl_y = 0; tpl_y < tpl_height; ++tpl_y) {
  108. const stbi_uc* p_org = source +
  109. (static_cast<size_t>(youter + tpl_y) * static_cast<size_t>(width) +
  110. static_cast<size_t>(xouter)) * static_cast<size_t>(channels);
  111. const stbi_uc* p_tpl = rgb_template + static_cast<size_t>(tpl_y) * templateRowLength;
  112. uint64_t rowSAD = 0;
  113. for (size_t tpl_x = 0; tpl_x < templateRowLength; tpl_x += static_cast<size_t>(channels)) {
  114. for (int ch = 0; ch < anzChannels; ++ch) {
  115. const int diff = static_cast<int>(p_tpl[tpl_x + static_cast<size_t>(ch)]) -
  116. static_cast<int>(p_org[tpl_x + static_cast<size_t>(ch)]);
  117. rowSAD += static_cast<uint64_t>(diff * diff);
  118. }
  119. }
  120. aktSAD += rowSAD;
  121. if (aktSAD >= minSAD) break;
  122. }
  123. if (aktSAD < minSAD) {
  124. minSAD = aktSAD;
  125. _ref->found_x = xouter;
  126. _ref->found_y = youter;
  127. }
  128. if (esp_timer_get_time() >= nextYieldUs) {
  129. vTaskDelay(1);
  130. nextYieldUs = esp_timer_get_time() + 50000;
  131. }
  132. }
  133. }
  134. if (_ref->alignment_algo == 2) {
  135. CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y,
  136. min, avg, max, SAD, _ref->fastalg_SAD,
  137. _ref->fastalg_SAD_criteria);
  138. }
  139. _ref->fastalg_x = _ref->found_x;
  140. _ref->fastalg_y = _ref->found_y;
  141. _ref->fastalg_min = min;
  142. _ref->fastalg_avg = avg;
  143. _ref->fastalg_max = max;
  144. _ref->fastalg_SAD = SAD;
  145. if (sourceLocked) RGBImageRelease();
  146. stbi_image_free(rgb_template);
  147. return false;
  148. }
  149. // Compares the template with the image at (_startx, _starty) and reports whether the match is still as
  150. // good as the stored one. Used by the "Fast" alignment to skip the full search.
  151. bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _starty, int &min, float &avg, int &max, float &SAD, float _SADold, float _SADcrit)
  152. {
  153. int dif;
  154. int minDif = 255;
  155. int maxDif = -255;
  156. double avgDifSum = 0;
  157. long int anz = 0;
  158. double aktSAD = 0;
  159. int xouter, youter, _ch;
  160. // The template has to lie completely inside the image at this position.
  161. if (_rgb_tmpl == NULL || rgb_image == NULL || width <= 0 || height <= 0 ||
  162. channels <= 0 || tpl_width <= 0 || tpl_height <= 0 ||
  163. _startx < 0 || _starty < 0 || tpl_width > width || tpl_height > height ||
  164. _startx > width - tpl_width || _starty > height - tpl_height) return false;
  165. // Walk the template, not the search area: the former loop ran over the search area size (plus one)
  166. // and so read past the end of the template buffer and compared pixels that are not part of the marker.
  167. for (xouter = 0; xouter < tpl_width; xouter++)
  168. for (youter = 0; youter < tpl_height; ++youter)
  169. {
  170. stbi_uc* p_org = rgb_image + (channels * ((youter + _starty) * width + (xouter + _startx)));
  171. stbi_uc* p_tpl = _rgb_tmpl + (channels * (youter * tpl_width + xouter));
  172. for (_ch = 0; _ch < channels; ++_ch)
  173. {
  174. dif = (int)p_tpl[_ch] - (int)p_org[_ch];
  175. aktSAD += dif * dif;
  176. if (dif < minDif) minDif = dif;
  177. if (dif > maxDif) maxDif = dif;
  178. avgDifSum += dif;
  179. anz++;
  180. }
  181. }
  182. if (anz == 0) return false;
  183. avg = avgDifSum / anz;
  184. min = minDif;
  185. max = maxDif;
  186. SAD = sqrt(aktSAD) / anz;
  187. float _SADdif = abs(SAD - _SADold);
  188. ESP_LOGD(TAG, "Anzahl %ld, avgDifSum %fd, avg %f, SAD_neu: %fd, _SAD_old: %f, _SAD_crit:%f", anz, avgDifSum, avg, SAD, _SADold, _SADdif);
  189. if (_SADdif <= _SADcrit)
  190. return true;
  191. return false;
  192. }