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

Re: [pygame] ChangeColor Routine



I thought this might work.  But == does not work on the [1,1,1].  It
only works on the each element.  Not sure how to make it do that.


def abrokenway(pic, oldcolor, newcolor):
    array = pygame.surfarray.pixels3d(pic)
    mask = Numeric.where(array == oldcolor, 1, 0)
    Numeric.putmask(array, mask, newcolor)


I can't think of any numeric magic to do this simple thing.  I think a
C function might be the trick here :)





On Fri, 11 Feb 2005 15:54:22 -0800, Kamilche <klachemin@xxxxxxxxxxx> wrote:
> '''
> 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()
> 
>