Searching for patterns on the screen

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Sep 15 10:52:47 EDT 2006


"Jerry Hill" <malaclypse2 at gmail.com> wrote in message 
news:mailman.125.1158327884.10491.python-list at python.org...
> Hello all,
>
> I have a piece of code I could use some help optimizing.  What I'm
> attempting to do is periodically grab a screenshot, and search for 2D
> patterns of black pixels in it.  I don't care about any color other
> than black.  Here's some simple code that simulates my worst-case
> scenario, scanning the whole screen for a sequence that does not
> exist:
>
> import ImageGrab  # From the PIL library
>
> def removeColor(rgb):
>    r, g, b = rgb
>    return (r == 0 and g == 0 and b == 0)
>
> BMP = ImageGrab.grab.getdata()
> x = map(removeColor, BMP)
>
> The idea is to search for sequences of black pixels on a background
> that can change colors.

I had to do a similar thing using pywinauto to interact with a IE browser 
running an embedded Flash application.  To speed things up, I included psyco 
to compile my functions.

As far as working just in Python, you could remove the tuple unpacking 
inside removeColor, and shorten it to just:

def removeColor(rgb):
    return rgb==(0,0,0)

or even better:

BLACK = (0,0,0)
def removeColor(rgb):
    return rgb==BLACK

By defining BLACK once and just referring to it by name, you also avoid 
dynamically constructing the (0,0,0) tuple in every call.

But you might also look at the PIL docs and see if there is a way to do this 
color manipulation using the PIL API - the advantage here is that then you 
would be invoking a C-compiled API routine, which will run way faster than 
any optimized Python method.

-- Paul






More information about the Python-list mailing list