截图&比较图像

时间:2015-07-25 22:28:05

标签: c#

我使用下面的这些功能来截取用户屏幕的屏幕截图,并将此屏幕截图与资源中的图像 bmpTest 进行比较。如果找到与 bmpTest 兼容的内容,则返回它的位置。

我的问题是:使用此算法有点慢,需要 10-15秒来解释图像并给出结果。你们中的任何人都知道其他同样但速度更快的方法吗?也许,有一些相似性?我无法在互联网上找到。

      private Bitmap Screenshot()
    {
        // this is where we will store a snapshot of the screen
        Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

        // creates a graphics object so we can draw the screen in the bitmap (bmpScreenshot)
        Graphics g = Graphics.FromImage(bmpScreenshot);

        // copy from screen into the bitmap we created
        g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);

        //g.CopyFromScreen(205, 179, 660, 241, new Size(455, 62));

       // return the screenshot
        return bmpScreenshot;
    }


    private bool FindBitmap(Bitmap bmpNeedle, Bitmap bmpHaystack, out Point location)
    {
        for (int outerX = 0; outerX < bmpHaystack.Width - bmpNeedle.Width; outerX++)
        {
            for (int outerY = 0; outerY < bmpHaystack.Height - bmpNeedle.Height; outerY++)
            {
                for (int innerX = 0; innerX < bmpNeedle.Width; innerX++)
                {
                    for (int innerY = 0; innerY < bmpNeedle.Height; innerY++)
                    {
                        Color cNeedle = bmpNeedle.GetPixel(innerX, innerY);
                        Color cHaystack = bmpHaystack.GetPixel(innerX + outerX, innerY + outerY);

                        if (cNeedle.R != cHaystack.R || cNeedle.G != cHaystack.G || cNeedle.B != cHaystack.B)
                        {
                            goto notFound;
                        }
                    }
                }
                location = new Point(outerX, outerY);
                return true;
            notFound:
                continue;
            }
        }
        location = Point.Empty;
        return false;
    }



    private void button8_Click_1(object sender, EventArgs e)
    {
        // takes a snapshot of the screen
        Bitmap bmpScreenshot = Screenshot();

        // find the login button and check if it exists
        Point location;
        bool success = FindBitmap(Properties.Resources.bmpTest, bmpScreenshot, out location);

        // check if it found the bitmap
        if (success == false)
        {
            MessageBox.Show("Not Found");
            return;
        }
        else
        {
            MessageBox.Show("Image Found");
        }            
    }

1 个答案:

答案 0 :(得分:0)

这是因为位图对象上的每个“GetPixel”调用都会执行锁定,从而导致性能问题。

你可以通过自己处理锁来获得更好的性能,这样你就可以锁定整个位图一次,在你的情况下都是两个位图,然后迭代它的像素。

Check out the code example by Vano Maisuradze