Python Imaging Library (PIL)
Posted by Troudeloup (Troudeloup), 1 July 2007import time
import ImageGrab # Part of PIL
from ctypes import *
# Load up the Win32 APIs we need to use.
_fields_ = [
GetForegroundWindow = windll.user32.GetForegroundWindow
GetWindowRect = windll.user32.GetWindowRect
# Sleep for 2 seconds - click the window you want to grab.
# Grab the foreground window's screen rectangle.
rect = RECT()
foreground_window = GetForegroundWindow()
image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom))
# Save the screenshot as a BMP.
# Get the pixel 10 pixels along the top of the foreground window - this
# will be a piece of the window border.
x = 0
y = 0
while x < 400:
while y < 20:
rgb = image.getpixel((10, 0))
y = y + 1
y = 0
x = x + 1
# PIL returns colours as RGB values packed into a triple:
print "RGB(%d, %d, %d)" % (rgb, rgb, rgb) # This prints RGB(0, 74, 216) on my XP machine
What that does is to take a screen shot and then pixelgetcolor() over 8000 (x,y) points
for me it clocked at 0.08 seconds and I am trying cut it down to maybe 0.04
any hints on performance increase?
Posted by admin (Graham Ellis), 1 July 2007Hmm ... that is very much a benchmark program; I'm not sure that you'll cut it down much with two tight loops of "getpixel" - you may shave a little off it with two nested for loops and xrange. What you need to do is to look wider - WHY are you picking up individual pixels with individual calls in the first place?
Not in Python but in other languages ... I have done graphic / pixel manipulation work in the past. Much better to use an alternative function / method that returns you a block of points rather than one at a time as that way the tight looping is done at what I describe as the "C" level. I don't know the PIL options personally - not one I've used - but that's where I would explore.
By the way, if you can give us a widfer view, I may have be able to make some more useful suggestions.
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: email@example.com • WEB: http://www.wellho.net • SKYPE: wellho