c++ - OpenCV模板匹配参数

标签 c++ opencv

在下面的模板匹配代码中,我不明白下面一行在做什么:

cv::Mat res(ref.rows-tpl.rows+1, ref.cols-tpl.cols+1, CV_32FC1);

完整代码为:

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

int main()
{
    cv::Mat ref = cv::imread("ref.jpg");
    cv::Mat tpl = cv::imread("temp.jpg");
    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;
}

最佳答案

它正在创建将包含匹配结果的矩阵。

根据 matchTemplate 的文档

  • result – 比较结果图。必须是单 channel 32位 float 。如果图像为 W x H ,模板为 w x h ,则结果为 (W-w+1) x (H-h+1)。

引用您的代码:

image    -> ref
template -> tpl
W        -> ref.cols
H        -> ref.rows
w        -> tpl.cols
h        -> tpl.rows 

single-channel 32-bit floating-point -> CV_32FC1

但是,由于 matchTemplate 将创建结果图像,因此您无需创建它。您可以简单地:

...
cv::Mat res;
cv::matchTemplate(gref, gtpl, res, CV_TM_CCOEFF_NORMED);
...

关于c++ - OpenCV模板匹配参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144829/

相关文章:

c++ - 使用 openCV c++ 示例代码执行抓取后保存输出图像

python - 如何在Python中实现流水线?

c++ - 函数参数的默认值

c++ - 如何在 Linux 平台上使用 C++ 中的 gTest 检测内存泄漏

c++ - 如何将二维数组的行(和列)相加

c# - 使用 OpenCV 感知二维图像中长方体的尺寸(或突出点)

c# - 在 Emgu 或 opencv 中组合多个图像

c++ - 将 float 打印为十进制并修复错误的输出

c++ - 是否可以在 C++ 中动态创建一个恒定大小的数组?

python - OpenCV VideoCapture 未打开