如何显示来自 OpenCV.MatchTemplate 的绘制矩形

How to display draw rectangle from OpenCV.MatchTemplate

我想在屏幕截图中找到一张图片并在其周围画一个矩形。我不明白如何解释我的 result 矩阵来识别包含图像的区域。

下面的代码将绘制一个矩形,但它并不是在正确的位置,我不知道那是因为我没有正确使用 result 还是其他原因。

using (Mat templateImage = CvInvoke.Imread("\top_1.png", Emgu.CV.CvEnum.ImreadModes.AnyColor))
using (Mat inputImage = CvInvoke.Imread(AppDomain.CurrentDomain.BaseDirectory + "\currentScreen.png", Emgu.CV.CvEnum.ImreadModes.AnyColor))
{
    Mat result = new Mat();
    CvInvoke.MatchTemplate(inputImage, templateImage, result, Emgu.CV.CvEnum.TemplateMatchingType.SqdiffNormed);

    result.MinMax(out double[] minVal, out double[] maxVal, out Point[] minLoc, out Point[] maxLoc);

    int x = minLoc[0].X;
    int y = minLoc[0].Y;
    int w = maxLoc[0].X - minLoc[0].X;
    int h = maxLoc[0].Y - minLoc[0].Y;

    Form f = new Form
    {
        BackColor = Color.Red,
        //TransparencyKey = Color.Red,
        FormBorderStyle = FormBorderStyle.None,
        TopMost = true,
        Location = new Point(x, y),
        Size = new Size(w, h)
    };

    Application.EnableVisualStyles();
    Application.Run(f);
}

我唯一看到的是表格的位置,您必须将 StarPosition 设置为 Manual

            Form f = new Form
            {
                StartPosition = FormStartPosition.Manual,
                BackColor = Color.Red,
                //TransparencyKey = Color.Red,
                FormBorderStyle = FormBorderStyle.None,
                TopMost = true,
                Location = new Point(x, y),
                Size = new Size(w, h)
            };

This is the screen Image

This is the template

This is the result

This is with out StartPosition

在阅读并重新阅读文档几次后,我意识到了我的错误。我最终没有使用它,因为我为我的用例找到了一种更简单、更可靠的方法,但为了其他人的利益:

函数 MinMax() 为您提供最小值和最大值,因为您使用哪个取决于所使用的匹配类型。例如 Emgu.CV.CvEnum.TemplateMatchingType.SqdiffNormed returns 最小值是最匹配的结果。

minLoc 中返回的位置只是 templateImage 的左上角坐标,因此它在与 templateImage 相同大小的区域上匹配,这意味着我只需要做:

int x = minLoc[0].X;
int y = minLoc[0].Y;
int w = maxLoc[0].X + templateImage.Width;
int h = maxLoc[0].Y + templateImage.Height;

我被抓了,因为我没有假设在 inputImage 中找到的 templateImage 大小相同。