visual-c++opencvmatchtemplate

OpenCV MatchTemplate limited to roi


My question is related to the use of matchTemplate in OpenCV. I'm able to use the function to find a template within the whole image. It is possible to limit the "searching area" to a restricted region within the image, i.e. using the roi? I tried to set the roi before calling matchTemplate but that didn't have any effect.

So, do you know any way to limit the search of the template to a subregion of the image? That because I know that my target can be found only in this limited region.

Here is some line of code taken directly from the OpenCV samples:

void MatchingMethod( int, void* )
{
    // Source image to display    
    Mat img_display;
    img.copyTo( img_display );

    // Create the result matrix
    int result_cols =  img.cols - templ.cols + 1;
    int result_rows = img.rows - templ.rows + 1;
    result.create( result_cols, result_rows, CV_32FC1 );

    // Do the Matching and Normalize
    img.adjustROI(100, 100, 500, 500);
    matchTemplate( img, templ, result, match_method );
    normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

    // Localizing the best match with minMaxLoc
    double minVal; double maxVal; Point minLoc; Point maxLoc;
    Point matchLoc;
    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

    // For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
    if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
    else
    { matchLoc = maxLoc; }

    // Show me what you got
    rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
    rectangle( result,    matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );

    imshow( image_window, img_display );
    imshow( result_window, result );
}

Solution

  • sure !

    Rect roi( x,y,w,h );
    matchTemplate( img( roi ), templ, result, method );