Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PIL (Python Image Library) to detect image on screen

I am trying to understand how I can use PIL in Python 2.7 to search the whole screen for a certain image and click on it. I've been searching around and haven't been able to find a solution. I want to create a small GUI with one button in the middle of it that when clicked will search the entire screen for a predefined image. Once the image is found the program will then click in the centre of it and end. In short the program will detect if an image is present on the users screen and click it.

I did find an interesting bit on Sikuli, but that doesn't help me because it's unable to export to an .exe.

The image that the program will look for will most likely be in the same place each time it searches, but I didn't want to hard-code the location as it has the potential to move and I don't want that being an issue later on.

What I need is the code method I would use to search for the image on screen and send back the cords to a variable.

Image explanation/example: Image

Reference image of rifle: Image2

like image 838
Freddie Avatar asked Dec 07 '14 15:12

Freddie


People also ask

How do I use PIL to display an image?

Python – Display Image using PIL To show or display an image in Python Pillow, you can use show() method on an image object. The show() method writes the image to a temporary file and then triggers the default program to display that image. Once the program execution is completed, the temporary file will be deleted.

Can I display image in full screen mode with PIL?

In order for it to open that program in full screen, PIL would need to know what arguments to send the program. There is no standard syntax for that. Thus, it is impossible.


1 Answers

PIL is the wrong tool for this job. Instead you should look into openCV (open source computer vision), which has fantastic python bindings. Here is a link to an example (in C but should be easy to redo with the python bindings) that does what you are looking for, but even allows the image to be rotated, scaled, etc.

http://docs.opencv.org/doc/tutorials/features2d/feature_homography/feature_homography.html http://docs.opencv.org/doc/tutorials/features2d/detection_of_planar_objects/detection_of_planar_objects.html

Edit:

I assume you are using windows, as your example image looks like window. In this case you can use:

from PIL import ImageGrab
pil_img = ImageGrab.grab()
opencv_img = numpy.array(pil_img)

then use opencv to process the image to find sub image you are looking for.

If you want to do this cross platform, then you will need to use wxWidgets to do the screengrab: https://stackoverflow.com/a/10089645/455532

like image 51
Kyle Avatar answered Oct 27 '22 15:10

Kyle