CFindTemplate.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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)
  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. uint8_t* source = RGBImageLock();
  48. if (source == NULL) {
  49. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image is locked");
  50. stbi_image_free(rgb_template);
  51. return false;
  52. }
  53. if (_ref->search_x == 0) {
  54. _ref->search_x = width;
  55. _ref->found_x = 0;
  56. }
  57. if (_ref->search_y == 0) {
  58. _ref->search_y = height;
  59. _ref->found_y = 0;
  60. }
  61. const int64_t leftCandidate = static_cast<int64_t>(_ref->target_x) - _ref->search_x;
  62. const int64_t rightCandidate = static_cast<int64_t>(_ref->target_x) + _ref->search_x;
  63. const int64_t topCandidate = static_cast<int64_t>(_ref->target_y) - _ref->search_y;
  64. const int64_t bottomCandidate = static_cast<int64_t>(_ref->target_y) + _ref->search_y;
  65. const int ow_start = static_cast<int>(std::max<int64_t>(0, leftCandidate));
  66. const int ow_stop = static_cast<int>(std::min<int64_t>(rightCandidate, width - tpl_width));
  67. const int oh_start = static_cast<int>(std::max<int64_t>(0, topCandidate));
  68. const int oh_stop = static_cast<int>(std::min<int64_t>(bottomCandidate, height - tpl_height));
  69. if (ow_stop < ow_start || oh_stop < oh_start) {
  70. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: search window does not intersect source image");
  71. RGBImageRelease();
  72. stbi_image_free(rgb_template);
  73. return false;
  74. }
  75. float avg = 0, SAD = 0;
  76. int min = 0, max = 0;
  77. bool isSimilar = false;
  78. if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1)) {
  79. isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y,
  80. min, avg, max, SAD, _ref->fastalg_SAD,
  81. _ref->fastalg_SAD_criteria);
  82. }
  83. if (isSimilar) {
  84. #ifdef DEBUG_DETAIL_ON
  85. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment successful");
  86. #endif
  87. _ref->found_x = _ref->fastalg_x;
  88. _ref->found_y = _ref->fastalg_y;
  89. RGBImageRelease();
  90. stbi_image_free(rgb_template);
  91. return true;
  92. }
  93. uint64_t aktSAD;
  94. uint64_t minSAD = UINT64_MAX;
  95. const int anzChannels = (_ref->alignment_algo == 0) ? 1 : channels;
  96. const size_t templateRowLength = static_cast<size_t>(tpl_width) * static_cast<size_t>(channels);
  97. int64_t nextYieldUs = esp_timer_get_time() + 50000;
  98. for (int xouter = ow_start; xouter <= ow_stop; ++xouter) {
  99. for (int youter = oh_start; youter <= oh_stop; ++youter) {
  100. aktSAD = 0;
  101. for (int tpl_y = 0; tpl_y < tpl_height; ++tpl_y) {
  102. const stbi_uc* p_org = source +
  103. (static_cast<size_t>(youter + tpl_y) * static_cast<size_t>(width) +
  104. static_cast<size_t>(xouter)) * static_cast<size_t>(channels);
  105. const stbi_uc* p_tpl = rgb_template + static_cast<size_t>(tpl_y) * templateRowLength;
  106. uint64_t rowSAD = 0;
  107. for (size_t tpl_x = 0; tpl_x < templateRowLength; tpl_x += static_cast<size_t>(channels)) {
  108. for (int ch = 0; ch < anzChannels; ++ch) {
  109. const int diff = static_cast<int>(p_tpl[tpl_x + static_cast<size_t>(ch)]) -
  110. static_cast<int>(p_org[tpl_x + static_cast<size_t>(ch)]);
  111. rowSAD += static_cast<uint64_t>(diff * diff);
  112. }
  113. }
  114. aktSAD += rowSAD;
  115. if (aktSAD >= minSAD) break;
  116. }
  117. if (aktSAD < minSAD) {
  118. minSAD = aktSAD;
  119. _ref->found_x = xouter;
  120. _ref->found_y = youter;
  121. }
  122. if (esp_timer_get_time() >= nextYieldUs) {
  123. vTaskDelay(1);
  124. nextYieldUs = esp_timer_get_time() + 50000;
  125. }
  126. }
  127. }
  128. if (_ref->alignment_algo == 2) {
  129. CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y,
  130. min, avg, max, SAD, _ref->fastalg_SAD,
  131. _ref->fastalg_SAD_criteria);
  132. }
  133. _ref->fastalg_x = _ref->found_x;
  134. _ref->fastalg_y = _ref->found_y;
  135. _ref->fastalg_min = min;
  136. _ref->fastalg_avg = avg;
  137. _ref->fastalg_max = max;
  138. _ref->fastalg_SAD = SAD;
  139. RGBImageRelease();
  140. stbi_image_free(rgb_template);
  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.
  155. if (_rgb_tmpl == NULL || rgb_image == NULL || width <= 0 || height <= 0 ||
  156. channels <= 0 || tpl_width <= 0 || tpl_height <= 0 ||
  157. _startx < 0 || _starty < 0 || tpl_width > width || tpl_height > height ||
  158. _startx > width - tpl_width || _starty > height - tpl_height) return false;
  159. // Walk the template, not the search area: the former loop ran over the search area size (plus one)
  160. // and so read past the end of the template buffer and compared pixels that are not part of the marker.
  161. for (xouter = 0; xouter < tpl_width; xouter++)
  162. for (youter = 0; youter < tpl_height; ++youter)
  163. {
  164. stbi_uc* p_org = rgb_image + (channels * ((youter + _starty) * width + (xouter + _startx)));
  165. stbi_uc* p_tpl = _rgb_tmpl + (channels * (youter * tpl_width + xouter));
  166. for (_ch = 0; _ch < channels; ++_ch)
  167. {
  168. dif = (int)p_tpl[_ch] - (int)p_org[_ch];
  169. aktSAD += dif * dif;
  170. if (dif < minDif) minDif = dif;
  171. if (dif > maxDif) maxDif = dif;
  172. avgDifSum += dif;
  173. anz++;
  174. }
  175. }
  176. if (anz == 0) return false;
  177. avg = avgDifSum / anz;
  178. min = minDif;
  179. max = maxDif;
  180. SAD = sqrt(aktSAD) / anz;
  181. float _SADdif = abs(SAD - _SADold);
  182. ESP_LOGD(TAG, "Anzahl %ld, avgDifSum %fd, avg %f, SAD_neu: %fd, _SAD_old: %f, _SAD_crit:%f", anz, avgDifSum, avg, SAD, _SADold, _SADdif);
  183. if (_SADdif <= _SADcrit)
  184. return true;
  185. return false;
  186. }