CFindTemplate.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "CFindTemplate.h"
  2. void CFindTemplate::FindTemplate(std::string _template, int* found_x, int* found_y)
  3. {
  4. FindTemplate(_template, found_x, found_y, 0, 0);
  5. }
  6. void CFindTemplate::FindTemplate(std::string _template, int* found_x, int* found_y, int _dx, int _dy)
  7. {
  8. uint8_t* rgb_template = stbi_load(_template.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
  9. int ow, ow_start, ow_stop;
  10. int oh, oh_start, oh_stop;
  11. if (_dx == 0)
  12. {
  13. _dx = width;
  14. *found_x = 0;
  15. }
  16. if (_dy == 0)
  17. {
  18. _dy = height;
  19. *found_y = 0;
  20. }
  21. ow_start = *found_x - _dx;
  22. ow_start = std::max(ow_start, 0);
  23. ow_stop = *found_x + _dx;
  24. if ((ow_stop + tpl_width) > width)
  25. ow_stop = width - tpl_width;
  26. ow = ow_stop - ow_start + 1;
  27. oh_start = *found_y - _dy;
  28. oh_start = std::max(oh_start, 0);
  29. oh_stop = *found_y + _dy;
  30. if ((oh_stop + tpl_height) > height)
  31. oh_stop = height - tpl_height;
  32. oh = oh_stop - oh_start + 1;
  33. uint8_t* odata = (unsigned char*)GET_MEMORY(ow * oh * channels);
  34. double aktSAD;
  35. double minSAD = pow(tpl_width * tpl_height * 255, 2);
  36. for (int xouter = ow_start; xouter <= ow_stop; xouter++)
  37. for (int youter = oh_start; youter <= oh_stop; ++youter)
  38. {
  39. aktSAD = 0;
  40. for (int tpl_x = 0; tpl_x < tpl_width; tpl_x++)
  41. for (int tpl_y = 0; tpl_y < tpl_height; tpl_y++)
  42. {
  43. stbi_uc* p_org = rgb_image + (channels * ((youter + tpl_y) * width + (xouter + tpl_x)));
  44. stbi_uc* p_tpl = rgb_template + (channels * (tpl_y * tpl_width + tpl_x));
  45. aktSAD += pow(p_tpl[0] - p_org[0], 2);
  46. }
  47. stbi_uc* p_out = odata + (channels * ((youter - oh_start) * ow + (xouter - ow_start)));
  48. p_out[0] = int(sqrt(aktSAD / (tpl_width * tpl_height)));
  49. if (aktSAD < minSAD)
  50. {
  51. minSAD = aktSAD;
  52. *found_x = xouter;
  53. *found_y = youter;
  54. }
  55. }
  56. stbi_write_bmp("sdcard\\find.bmp", ow, oh, channels, odata);
  57. stbi_image_free(odata);
  58. stbi_image_free(rgb_template);
  59. }
  60. void CFindTemplate::FindTemplate(std::string _template, int* found_x, int* found_y, std::string _imageout)
  61. {
  62. FindTemplate(_template, found_x, found_y);
  63. SaveToFile(_imageout);
  64. }
  65. void CFindTemplate::FindTemplate(std::string _template, int* found_x, int* found_y, int _dx, int _dy, std::string _imageout)
  66. {
  67. FindTemplate(_template, found_x, found_y, _dx, _dy);
  68. SaveToFile(_imageout);
  69. }