OpenCV MatchTemplate仅限于roi

时间:2013-08-08 07:30:58

标签: visual-c++ opencv matchtemplate

我的问题与在OpenCV中使用matchTemplate有关。我可以使用该功能在整个图像中查找模板。可以将“搜索区域”限制在图像内的受限区域,即使用roi?我试着在调用matchTemplate之前设置roi,但这没有任何效果。

那么,你知道如何将模板的搜索限制在图像的子区域吗?那是因为我知道我的目标只能在这个有限的地区找到。

以下是直接从OpenCV示例中获取的一些代码:

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 );
}

1 个答案:

答案 0 :(得分:1)

确定!

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