我正在尝试在图像中查找图像。我这样做是为了桌面自动化。此时此刻,我力求快,而不是精确。因此,我决定仅根据相同的平均颜色来匹配相似图像。
如果我在桌面上选择几个图标,例如:
然后我会搜索最后一个(我还在想这个文件是什么):
您可以清楚地看到最有可能匹配的内容:
在不同的情况下,这可能不起作用。但是,当给定图像大小时,它应该非常可靠且速度快如闪电。
我可以获取 BufferedImage
对象的屏幕截图:
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);
当然,要搜索的图像将从保存在文件中的模板中加载:
BufferedImage img = ImageIO.read(...whatever goes in there, I'm still confused...);
我解释了我所知道的,以便我们可以专注于唯一的问题:
- 问:如何获得缓冲图像的平均颜色?我怎样才能在该图像的子矩形上获得这样的平均颜色?
在这里速度取胜。在这种特殊情况下,我认为它比代码可读性更有值(value)。
最佳答案
我认为无论你做什么,你都会有一个O(wh)
操作,其中w
是你的宽度,h
是你的高度。
因此,我将发布这个(幼稚的)解决方案来解决您问题的第一部分,因为我认为没有更快的解决方案。
/*
* 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);
}
关于java - 尽快获得缓冲图像和缓冲图像部分的平均颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162488/