Reputation: 2075
Is there a fast way to find an Image on the Screen?
I did like that: (before that i captured the screen with Robot.createScreenCapture(...))
public static Point search(BufferedImage big, BufferedImage small) {
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
long time=System.currentTimeMillis();
for (int x = 0; x < big.getWidth() - small.getWidth(); x++) {
for (int y = 0; y < big.getHeight() - small.getHeight(); y++) {
if (compare(x, y, big, small)) {
return new Point(x, y);
}
}
}
System.out.println(System.currentTimeMillis()-time);
return null;
}
private static boolean compare(int xs, int ys, BufferedImage img1, BufferedImage img2) {
for (int x = 0; x < img2.getWidth(); x++) {
for (int y = 0; y < img2.getHeight(); y++) {
if (img1.getRGB(x + xs, y + ys) != img2.getRGB(x, y)) {
return false;
}
}
}
return true;
}
But it takes sometimes just 200ms but sometimes 10000ms! :(
Edit: If anybody knows Autohotkey, it's another programming language and there's a function called "ImageSearch" which finds those images in a few milliseconds... (based on C++ i think)
Upvotes: 0
Views: 3183
Reputation: 27180
Two possible things:
The algorithm you use is not really fast: it is an O(mn) algorithm, so you should probably looking into better ones such as the KMP algorithm.
Before searching for the image, probably first compress them then search, and use another check to make sure the compress did not affect the algorithm. A simple "take out the every other line" should speed up the program pretty much.
Upvotes: 3