如何从OpenCV.MatchTemplate显示绘制矩形

时间:2020-01-23 22:38:07

标签: c# opencv emgucv

我正在尝试在屏幕快照中查找图像并在其周围绘制一个矩形。我不了解如何解释我的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);
}

2 个答案:

答案 0 :(得分:0)

我唯一看到的是表单的位置,您必须将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

答案 1 :(得分:0)

在阅读并重新阅读了几次文档后,我意识到自己的错误。我最终没有使用此方法,因为我发现了一个用于用例的更简单,更可靠的方法,但是却为其他人带来了好处。

函数MinMax()可以为您提供最大值和最小值,因为您使用的是哪一种取决于所使用的匹配类型。例如Emgu.CV.CvEnum.TemplateMatchingType.SqdiffNormed返回结果,其中最小值是最大匹配项。

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;

我被发现是因为我不认为在templateImage中发现的inputImage具有相同的大小。

相关问题