I am trying to find image occurences inside an image. I have written the following code to get a single match using OpenCVSharp3:
Mat src = OpenCvSharp.Exten
I think that code should help you: http://opencv-code.com/quick-tips/how-to-handle-template-matching-with-multiple-occurences/
It's C++, but conversion to C# shouldn't be a big deal.
#include
#include
int main()
{
cv::Mat ref = cv::imread("reference.png");
cv::Mat tpl = cv::imread("template.png");
if (ref.empty() || tpl.empty())
return -1;
cv::Mat gref, gtpl;
cv::cvtColor(ref, gref, CV_BGR2GRAY);
cv::cvtColor(tpl, gtpl, CV_BGR2GRAY);
cv::Mat res(ref.rows-tpl.rows+1, ref.cols-tpl.cols+1, CV_32FC1);
cv::matchTemplate(gref, gtpl, res, CV_TM_CCOEFF_NORMED);
cv::threshold(res, res, 0.8, 1., CV_THRESH_TOZERO);
while (true)
{
double minval, maxval, threshold = 0.8;
cv::Point minloc, maxloc;
cv::minMaxLoc(res, &minval, &maxval, &minloc, &maxloc);
if (maxval >= threshold)
{
cv::rectangle(
ref,
maxloc,
cv::Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows),
CV_RGB(0,255,0), 2
);
cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
}
else
break;
}
cv::imshow("reference", ref);
cv::waitKey();
return 0;
}