当前位置:   article > 正文

图像识别基础之模板匹配

图像识别基础之模板匹配

principle

图像匹配

本质:图像的相似度很高(矩阵的相似度很高)

code

  1. /*
  2. \brief 我的图像匹配函数,获取差方和均值最小的矩阵作为结果
  3. \param srcPicFile:用以匹配的图像文件
  4. \param templatePicFile:模板图像文件
  5. \param destPicFile:输出的检测结果文件
  6. */
  7. void MyPictureMatch(const char* srcPicFile, const char* templatePicFile, const char* destPicFile)
  8. {
  9. if ((!srcPicFile) || (!templatePicFile) || (!destPicFile))
  10. {
  11. return;
  12. }
  13. cv::Mat srcMat;
  14. cv::Mat templateMat;
  15. cv::Mat srcGrayMat;
  16. cv::Mat templateGrayMat;
  17. uint32_t templateMatSize = 0;
  18. cv::Rect mask;
  19. cv::Mat subSrcGrayMat;
  20. cv::Mat caculationMat;
  21. struct recorde {
  22. int x;
  23. int y;
  24. double caculation;
  25. };
  26. recorde recorder;
  27. std::vector<recorde> recordes;
  28. srcMat = cv::imread(srcPicFile);
  29. templateMat = cv::imread(templatePicFile);
  30. if (srcMat.size < templateMat.size) {
  31. fprintf(stdout, "srcMat.size < templateMat.size\n");
  32. return;
  33. }
  34. templateMatSize = templateMat.cols * templateMat.rows;
  35. cv::cvtColor(srcMat, srcGrayMat,
  36. cv::ColorConversionCodes::COLOR_RGB2GRAY);
  37. cv::cvtColor(templateMat, templateGrayMat,
  38. cv::ColorConversionCodes::COLOR_RGB2GRAY);
  39. mask.width = templateGrayMat.cols;
  40. mask.height = templateGrayMat.rows;
  41. caculationMat.create(cv::Size(templateGrayMat.cols, templateGrayMat.rows), templateGrayMat.type());
  42. for (int i = 0; (i + mask.height) < srcGrayMat.rows; ++i)
  43. {
  44. for (int j = 0; (j + mask.width) < srcGrayMat.cols; ++j)
  45. {
  46. mask.x = j;
  47. mask.y = i;
  48. recorder.x = mask.x;
  49. recorder.y = mask.y;
  50. srcGrayMat(mask).copyTo(subSrcGrayMat);
  51. cv::subtract(subSrcGrayMat, templateGrayMat, caculationMat);
  52. cv::multiply(caculationMat, caculationMat, caculationMat);
  53. cv::Scalar sum = cv::sum(caculationMat);
  54. recorder.caculation = sum(0);
  55. recorder.caculation = recorder.caculation / templateMatSize;
  56. recordes.push_back(recorder);
  57. // fprintf(stderr, "recorder.caculation:%lf\n", recorder.caculation);
  58. }
  59. }
  60. auto cmp = [](const recorde& p1, const recorde& p2)->bool {
  61. if (p1.caculation < p2.caculation)
  62. {
  63. return true;
  64. }
  65. return false;
  66. };
  67. std::sort(recordes.begin(), recordes.end(), cmp);
  68. fprintf(stdout, "recordes[0]:%d,%d,%lf\n", recordes[0].x, recordes[0].y, recordes[0].caculation);
  69. mask.x = recordes[0].x;
  70. mask.y = recordes[0].y;
  71. cv::rectangle(srcMat, mask, cv::Scalar(0, 255, 0));
  72. // imshow需要显示驱动
  73. #if 0
  74. cv::imshow(destPicFile, srcMat);
  75. cv::waitKey();
  76. #else
  77. cv::imwrite(destPicFile, srcMat);
  78. #endif
  79. }

performance

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/101731
推荐阅读
相关标签
  

闽ICP备14008679号