Is try-except slow?

process circularfunc at gmail.com
Tue Sep 2 21:00:28 EDT 2008


On Sep 3, 2:36 am, John Machin <sjmac... at lexicon.net> wrote:
> On Sep 3, 9:44 am, ssecorp <circularf... at gmail.com> wrote:
>
> > or why does this take so god damn long time?
>
> Because your code does so many god damn unnecessary things. Apart from
> the fact (as pointed out already by Robert) that you are needlessly
> finding the sizes (Y, X) that are already available:
>
> (1) You are executing a try block Y*X (approx) times instead of the Y+X
> +2 times it would take if you were to do preliminary probes to find Y
> and X
> (2) You are doing range(1, 1000) Y times instead of once [see question
> below]
> (3) You are doing the method lookup im.getpixel Y*X times instead of
> once
> (4) you are doing the method lookup row.append Y*X times instead of Y
> times
>
> > and if I run into an IndexError it break out of the inner loop right?
> > so having range up to 10000000 or 1000 wouldn't matter if biggest
> > working x is 800?
>
> > def getPixels(fileName):
> >     im = PIL.Image.open(fileName)
> >     colors = []
> >     for y in range(1, 1000):
>
> Are you sure that both occurrences of range(1, 1000) shouldn't be
> range(1000)?
>
> >         row = []
> >         for x in range(1, 1000):
> >             try:
> >                 color = im.getpixel((x,y))
> >                 row.append(color)
> >             except IndexError:
> >                 break
> >             colors.append(row)
> >     return numpy.array(colors)
>
> and it appears that you haven't bothered to read the manual section on
> Image.getpixel:
> """
> Note that this method is rather slow; if you need to process larger
> parts of an image from Python, you can either use pixel access objects
> (see load), or the getdata method.
> """


how could I do getpixel once when x and y s changing?



anyway I rewrote and saw I did a lot of stupid stuff. this is fast:
def getPixels5(fileName):
    im = PIL.Image.open(fileName)
    colors = []
    r, c = im.size
    for y in range(0, c):
        row = []
        for x in range(0, r):
            color = im.getpixel((x,y))
            row.append(color)
        colors.append(row)
    return numpy.array(colors)

but I don't need it anuyway apparently since there already was such
methods :)



More information about the Python-list mailing list