CFindTemplate.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. RGBImageLock();
  37. for (int xouter = ow_start; xouter <= ow_stop; xouter++)
  38. for (int youter = oh_start; youter <= oh_stop; ++youter)
  39. {
  40. aktSAD = 0;
  41. for (int tpl_x = 0; tpl_x < tpl_width; tpl_x++)
  42. for (int tpl_y = 0; tpl_y < tpl_height; tpl_y++)
  43. {
  44. stbi_uc* p_org = rgb_image + (channels * ((youter + tpl_y) * width + (xouter + tpl_x)));
  45. stbi_uc* p_tpl = rgb_template + (channels * (tpl_y * tpl_width + tpl_x));
  46. aktSAD += pow(p_tpl[0] - p_org[0], 2);
  47. }
  48. stbi_uc* p_out = odata + (channels * ((youter - oh_start) * ow + (xouter - ow_start)));
  49. p_out[0] = int(sqrt(aktSAD / (tpl_width * tpl_height)));
  50. if (aktSAD < minSAD)
  51. {
  52. minSAD = aktSAD;
  53. *found_x = xouter;
  54. *found_y = youter;
  55. }
  56. }
  57. RGBImageRelease();
  58. stbi_write_bmp("sdcard\\find.bmp", ow, oh, channels, odata);
  59. stbi_image_free(odata);
  60. stbi_image_free(rgb_template);
  61. }
  62. void CFindTemplate::FindTemplate(std::string _template, int* found_x, int* found_y, std::string _imageout)
  63. {
  64. FindTemplate(_template, found_x, found_y);
  65. SaveToFile(_imageout);
  66. }
  67. void CFindTemplate::FindTemplate(std::string _template, int* found_x, int* found_y, int _dx, int _dy, std::string _imageout)
  68. {
  69. FindTemplate(_template, found_x, found_y, _dx, _dy);
  70. SaveToFile(_imageout);
  71. }