The code reads from the screen, compares a pixel in a previously provided sample image and, if the pixels match, it records timeback seconds of video leading up to it. The output is put into a folder 'tm'. Since I do not assume the pixel to be occurring all the time, the writing process is buffered with a thread, so as not to slow down the capturing process. The pictures in the folder 'tm' can in the end be combined to make up a shortened movie, containing all the frames with the pixel in place.
I don't even know where to start optimizing. What should I improve in terms of readability and speed?
import PIL.ImageGrab
import PIL.Image
import time
from collections import deque
import threading
from numpy import *
def get_pixel_colour(i_x, i_y):
return PIL.ImageGrab.grab().load()[i_x, i_y]
class framebuffer:
def __init__(self,size):
self.buffer = deque(maxlen=size)
self.i= 0
def add_frame(self, frame):
self.buffer.append(frame)
def remove_frame(self):
return self.buffer.popleft()
def write_frame(self):
x = self.buffer.popleft()
self.i+=1
x.save("tm\screengrab"+ str(self.i).zfill(10) +".jpg")
print "tm\screengrab"+ str(self.i).zfill(10) +".jpg written, ", len(self.buffer), "to go "
def is_empfty(self):
return (len(self.buffer)>0)
class mythread(threading.Thread):
def run (self):
while(True):
if (len(self.frameb.buffer) > 0):
self.frameb.write_frame()
else:
time.sleep(1)
def setbuffer(self,frameb):
self.frameb = frameb
seedimage = PIL.Image.open("seed.bmp")
pos_x = 983
pos_y = 263
recpixel = seedimage.load()[pos_x, pos_y]
print "The pixel is now", recpixel
fps = 50
skipticks = 1/(fps*1.0)
i= 0
timeback = fps * 3
allframes=framebuffer(timeback)
nextsnap=time.clock()
recordframes = framebuffer(None)
t= mythread()
t.setbuffer(recordframes)
print 'Starting thread'
t.setDaemon(True)
t.start()
print 'starting program'
print skipticks, fps
while (True):
tim= time.clock()
i=i+1
x = PIL.ImageGrab.grab()
allframes.add_frame(x)
imp_pixel = x.load()[pos_x, pos_y]
r, i = array(recpixel),array(imp_pixel)
if (sum(r-i)<1 and sum(r-i)>-1 ):
print "recognized", sum(r-i),"with size:", len(allframes.buffer)
recordframes.buffer.extend(allframes.buffer)
allframes.buffer.clear()
sleep(10)
# this is the sleep that limits the fps
nextsnap+=skipticks
sleeptime = nextsnap-time.clock()
if (sleeptime>0):
time.sleep (sleeptime)