简体   繁体   中英

opencv, template match

I'am using opencv for some project. And have a task which should be solved. Task is quite simple. I have a main picture and have a template(s) than I compare main pic with template. I use matchTemplate() function. I'am just curiosity about one moment. In documentation I found following info: To identify the matching area, we have to compare the template image against the source image by sliding it. By sliding, we mean moving the patch one pixel at a time (left to right, up to down). At each location, a metric is calculated so it represents how “good” or “bad” the match at that location is (or how similar the patch is to that particular area of the source image). For each location of T over I, you store the metric in the result matrix (R). Each location in R contains the match metric.

So, for example you have the main picture and the template. And you know that there is one entry of template at least in main pic. And it works fine. But if you do not know how many templates are in the main picture 0 or 10? Is any way to calculate it ? Which algorithm should be used? How I can understand what metric in the result matrix means? Thanks in advance.

The matchTemplate() function creates a new matrix where every pixel holds the value of how much the given template matches the image at that point. in order to detect all the areas that match the template you need to go over the result matrix and check for every pixel if it passes a certain threshold.
If a pixel passes the threshold that means that it is the top left corner of an area in the image that matches the template. a simple implementation might look like this:

double PATT_THRESH = 0.4
IplImage *result = cvCreateImage(cvSize(imageW, imageH), IPL_DEPTH_32F, 1);
vector<CvPoint> foundTemplates;
cvMatchTemplate(image, pattern, result, CV_TM_SQDIFF_NORMED);
for (int i = 0 ; i < result->width ; ++i) {
    for (int j = 0 ; j < result->height ; ++j) {
        if (cvGet2D(result, j, i).val[0] < PATT_THRESH) {
            foundTemplates.push_back(cvPoint(i, j);
        }
    }

}

I don't know what language you are using but it is easy to translate to other languages. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM