[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] ChangeColor Routine



'''
I'm writing a routine to replace all occurrences of
one color with another, in full color pictures.
Why does the 'faster' function below go faster,
when it uses get_at and set_at?
I thought those routines were slower than surfarrays.
'''

import pygame

def main():
    pygame.init()
    window = pygame.display.set_mode((100, 100), pygame.NOFRAME, 32)
    pic = pygame.Surface((100, 100), pygame.SRCALPHA)
    oldcolor = (255, 255, 0)
    newcolor = (255, 0, 255)
    timeit(window, faster, pic, oldcolor, newcolor)
    timeit(window, slower, pic, oldcolor, newcolor)
    pygame.quit()

def timeit(bg, fn, pic, oldcolor, newcolor):
    pic.fill(oldcolor)
    bg.blit(pic, (0, 0))
    pygame.display.flip()
    starttime = pygame.time.get_ticks()
    fn(pic, oldcolor, newcolor)
    elapsedtime = pygame.time.get_ticks() - starttime
    bg.blit(pic, (0, 0))
    pygame.display.flip()
    print "%s: %d milliseconds" % (fn.__name__, elapsedtime)

def faster(pic, oldcolor, newcolor):
    # This routine is faster, though it uses get_at.
    pic.lock()
    for x in range(pic.get_width()):
        for y in range(pic.get_height()):
            pixel = pic.get_at((x,y))
            if pixel == oldcolor:
                pic.set_at((x,y), newcolor)
    pic.unlock()

def slower(pic, oldcolor, newcolor):
    # This routine is slower, though it uses a pixel array
    maxx = range(pic.get_width())
    maxy = range(pic.get_height())
    array = pygame.surfarray.pixels3d(pic)
    for x in maxx:
        for y in maxy:
            if array[x, y] == oldcolor:
                array[x, y] = newcolor

main()