在缓冲图像和缓冲图像部分尽可能快地获得平均颜色 [英] Get average color on bufferedimage and bufferedimage portion as fast as possible

查看:344
本文介绍了在缓冲图像和缓冲图像部分尽可能快地获得平均颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在图片中找到图片。我这样做是为了桌面自动化。在这一刻,我想要快,不精确。

I am trying to find image in an image. I do this for desktop automation. At this moment, I'm trying to be fast, not precise. As such, I have decided to match similar image solely based on the same average color.

如果我在桌面上选择几个图标,例如:

If I pick several icons on my desktop, for example:

我将搜索最后一个(我仍然想知道这个文件是什么):

And I will search for the last one (I'm still wondering what this file is):

您可以清楚地看到什么是最可能的匹配:

You can clearly see what is most likely to be the match:

在不同的情况下,这可能不工作。

In different situations, this may not work. However when image size is given, it should be pretty reliable and lightning fast.

我可以得到一个截图作为 BufferedImage object:

I can get a screenshot as BufferedImage object:

MSWindow window = MSWindow.windowFromName("Firefox", false);
BufferedImage img = window.screenshot();
//Or, if I can estimate smaller region for searching:
BufferedImage img2 = window.screenshotCrop(20,20,50,50);

当然,图片搜索图片将从保存在文件中的模板加载:

Of course, the image to search image will be loaded from template saved in a file:

BufferedImage img = ImageIO.read(...whatever goes in there, I'm still confused...);

我解释了我所知道的一切,以便我们可以专注于唯一的问题:

I explained what all I know so that we can focus on the only problem:


  • 问:如何获得缓冲图像的平均颜色?如何在图片的子矩形上获得此类平均颜色?

  • Q: How can I get average color on buffered image? How can I get such average color on sub-rectangle of that image?

速度胜利在这里。在这个例外情况下,我认为它比代码可读性更有价值。

Speed wins here. In this exceptional case, I consider it more valuable than code readability.

推荐答案

我认为无论你做什么,将有一个 O(wh)操作,其中 w 是您的宽度和 / code>是你的身高。

I think that no matter what you do, you are going to have an O(wh) operation, where w is your width and h is your height.

因此,我要发布这个(天真的)解决方案来完成你的问题的第一部分,因为我不相信有更快的解决方案。

Therefore, I'm going to post this (naive) solution to fulfil the first part of your question as I do not believe there is a faster solution.

/*
 * Where bi is your image, (x0,y0) is your upper left coordinate, and (w,h)
 * are your width and height respectively
 */
public static Color averageColor(BufferedImage bi, int x0, int y0, int w,
        int h) {
    int x1 = x0 + w;
    int y1 = y0 + h;
    long sumr = 0, sumg = 0, sumb = 0;
    for (int x = x0; x < x1; x++) {
        for (int y = y0; y < y1; y++) {
            Color pixel = new Color(bi.getRGB(x, y));
            sumr += pixel.getRed();
            sumg += pixel.getGreen();
            sumb += pixel.getBlue();
        }
    }
    int num = w * h;
    return new Color(sumr / num, sumg / num, sumb / num);
}

这篇关于在缓冲图像和缓冲图像部分尽可能快地获得平均颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆