检查准确位置的准确图像是否在屏幕上

Check if exact image in exact location is on screen

我想在 Visual Studio (C#) 中创建一个程序,该程序扫描屏幕以在屏幕的确切位置找到准确的图像。我看到很多讨论涉及查找 "close" 图像的算法,但我的是 100% 准确的;位置、大小和所有。

我使用以下代码从我的屏幕 [图片 1] 的一部分获得了 png:

private void button1_Click(object sender, EventArgs e)
    {
        //Create a new bitmap.
        var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                       Screen.PrimaryScreen.Bounds.Height);

        // Create a graphics object from the bitmap.
        var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

        // Take the screenshot from the upper left corner to the right bottom corner.
        gfxScreenshot.CopyFromScreen(1555, 950, 
                                    1700, 1010,
                                    Screen.PrimaryScreen.Bounds.Size,
                                    CopyPixelOperation.SourceCopy);

        // Save the screenshot to the specified path that the user has chosen.
        bmpScreenshot.Save("Screenshot.png");
    }

所以,基本上这是我的程序流程图,说明我想如何前进: 1)使用上面的代码创建主png 2) 运行 循环: 使用与主 png 相同的程序创建相同的屏幕截图 将主 png 与新的截图 png 和 if:match 进行比较,然后继续,否则重复循环。

我是编程的新手,但我不认为这超出了我的范围,只要给予一点指导。我编写了相当复杂的(在我看来)VBA 和 Matlab 程序。任何帮助是极大的赞赏。

谢谢, 斯隆

仔细研究了 Microsoft 的文档,我想出了一个粗略的函数,可以执行与您想要的类似的操作。 https://msdn.microsoft.com/en-us/library/hh191601.aspx

此函数有可能陷入无限循环,因此您可以考虑在主函数中使用超时调用它。有关带超时的同步方法的信息,请参见此处: Monitoring a synchronous method for timeout

从你的主要角度来看,你所要做的就是看看它是否 returns 正确。

static int Main(string[] args)
{
   if (ImageInLocation(left, right, top, bottom)) {
      // do other things
   }

   return 0;
}

我唯一不能完全确定的是您对 ColorDifference 的严格程度。即使图像是相同的,具有完全不可容忍的 ColorDifference 的任何像素差异都将出现错误。如果您知道它应该起作用但它不起作用,也许可以考虑增加容差。这里有一些关于它的更多信息: https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.colordifference.aspx

public bool ImageInLocation(int left, int right, int top, int bottom) {
   bool image_found = false;
   var masterImage = Image.FromFile("path_to_master");

   while (!image_found) {
      // screenshot code above, output to "path_to/Screenshot.jpg"
      var compImage = Image.FromFile("path_to/Screenshot.jpg");

      // note, all zeroes may not be tolerant enough
      var color_diff = new ColorDifference(0, 0, 0, 0); 
      Image diffImage;

      image_found = ImageComparer.Compare(masterImage, compImage, color_diff, out diffImage);
   }

   return true;
}

祝你好运!欢迎来到编程社区。

此外,如果有人有任何 suggestions/changes,请随时编辑。祝朋友们成像愉快!