[Tutor] speeding code along

Thomi Richards thomi@thomi.imail.net.nz
Sun Nov 17 17:29:01 2002


hey guys, thanks for your previous help with hex and tKinter. I've got
it finished now. My question is:

How can i speed up the following code?  take a look: it is called
several thousand times, and i would like to speed it up just a little...

it takes (on average) around 45 seconds for teh entire program to run,
and this function is where 99% of the time is being spent. i checked
with the profiler:

-----<snip>------
#!/usr/bin/python2.2

import sys
import os
from math import sqrt
from string import split
import Image

if __name__ == "__main__":
        print 'Please run the "convert.py" file. This file only contains
the math algorithm to convert pixels to colors in the palette'
        sys.exit(0)


def convert(filename,inpalette,extension='-converted'):
        convfile = Image.open('input/%s' % (filename))
        if convfile.mode != 'RGB':
                temp = convfile.convert('RGB')
                convfile = temp
                del(temp)
        
        for x in range(convfile.size[0] - 1):
                for y in range(convfile.size[1] - 1):
                        pixel = convfile.getpixel((x,y))
                        tempdistance = 6000
                        for color in inpalette:
                                distance = sqrt( (color[0] -
pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 )
                                if distance < tempdistance:
                                        tempdistance = distance
                                        tempcolor = color
                                if tempdistance == 0:
                                        break
                        convfile.putpixel((x,y),tempcolor)
        
        #now we save the file!
        convfile.save('output/%s%s.bmp' %
(split(filename,'.')[0],extension))
        return 0
------</snip>------

thanks. I realise i could try writing it in C, but i thought maybe there
were some things i am doing wrong in python....

-- 
Thomi Richards
thomi@imail.net.nz
http://ddmodd.sourceforge.net/
Thomi Richards,
thomi@imail.net.nz