473,386 Members | 1,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Is try-except slow?

or why does this take so god damn long time?
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):
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)

Sep 2 '08 #1
9 3976
ssecorp wrote:
or why does this take so god damn long time?
Several reasons. One of which is that try: except: is slow.
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?
try: except: needs to set up a few things before the try: suite is executed. You
pay this cost regardless of whether the exception fires or not.
def getPixels(fileName):
im = PIL.Image.open(fileName)
colors = []
for y in range(1, 1000):
row = []
for x in range(1, 1000):
try:
color = im.getpixel((x,y))
row.append(color)
except IndexError:
break
Images have a size tuple attached to them. I recommend using that to get the
upper bounds of the iterations.
colors.append(row)
return numpy.array(colors)
Or, with reasonably modern versions of PIL and numpy:
In [1]: import Image

In [2]: im = Image.open('lena.png')

In [3]: import numpy

In [4]: numpy.asarray(im)
Out[4]:
array([[[228, 134, 132],
[228, 134, 132],
[228, 135, 130],
...,
[244, 151, 136],
[227, 132, 114],
[197, 102, 82]],

[[228, 135, 130],
[228, 135, 130],
[228, 135, 130],
...,
[237, 145, 124],
[219, 127, 102],
[191, 100, 73]],

[[227, 134, 129],
[227, 134, 129],
[227, 134, 127],
...,
[236, 147, 117],
[216, 130, 97],
[192, 106, 71]],

...,
[[ 87, 22, 56],
[ 89, 24, 58],
[ 90, 25, 59],
...,
[178, 67, 76],
[180, 65, 72],
[179, 62, 70]],

[[ 87, 22, 56],
[ 88, 23, 57],
[ 90, 25, 59],
...,
[183, 68, 75],
[188, 67, 72],
[190, 67, 72]],

[[ 86, 21, 55],
[ 88, 23, 57],
[ 90, 25, 59],
...,
[186, 70, 73],
[193, 70, 73],
[195, 71, 73]]], dtype=uint8)
--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Sep 3 '08 #2
On Sep 3, 9:44 am, ssecorp <circularf...@gmail.comwrote:
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.
"""

Sep 3 '08 #3
On Sep 3, 2:36*am, John Machin <sjmac...@lexicon.netwrote:
On Sep 3, 9:44 am, ssecorp <circularf...@gmail.comwrote:
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 :)
Sep 3 '08 #4
is this faster btw? I guess big doesn't help, it's only retrieved once
anyway? But is rows retrieved in every loop? the python interpreter
aint too smart?

def getPixels(fileName):
im = PIL.Image.open(fileName)
colors = []
r, c = im.size
big = range(0, c)
rows = range(0, r)
for y in big:
row = []
for x in rows:
color = im.getpixel((x,y))
row.append(color)
colors.append(row)
return numpy.array(colors)
Sep 3 '08 #5
On Sep 3, 11:00 am, process <circularf...@gmail.comwrote:
how could I do getpixel once when x and y s changing?
I was not referring to *calling* im.getpixel, I was referring to
looking up getpixel as an attribute of im. How? See below.
>
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
im_getpixel = im.getpixel
for y in range(0, c):
row = []
for x in range(0, r):
color = im.getpixel((x,y))
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 :)
Sep 3 '08 #6
On Sep 3, 11:14 am, process <circularf...@gmail.comwrote:
is this faster btw?
Time it and see.
I guess big doesn't help, it's only retrieved once
anyway?
Correct.
But is rows retrieved in every loop?
Of course. Read your own code! The point is that retrieving the list
referenced by "rows" is much faster than creating it needlessly each
time.
the python interpreter
aint too smart?
It's smarter than some. The trade-off for having a very dynamic
language is that some compile-time optimisations are more difficult.
If you are interested in work (being)? done in this area, look at
psyco and PyPy.

Sep 3 '08 #7
On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote:
ssecorp wrote:
>or why does this take so god damn long time?

Several reasons. One of which is that try: except: is slow.

I beg to differ. Setting up a try...except block is very fast. Here's an
example in Python 2.5:

>>from timeit import Timer
Timer('len("abc")').repeat()
[0.27346706390380859, 0.1530919075012207, 0.14886784553527832]
>>Timer('''try:
.... len("abc")
.... except:
.... pass
.... ''').repeat()
[0.27847194671630859, 0.19191384315490723, 0.19077491760253906]

The difference (approx 0.04 microseconds) applicable to setting up the
try...except block is trivial, of the same magnitude as a pass statement:
>>Timer('pass').repeat()
[0.059719085693359375, 0.060056924819946289, 0.059512138366699219]
However, *catching* the exception may be relatively slow:
>>Timer('''try:
.... len(abc) # raise a NameError
.... except:
.... pass
.... ''').repeat()
[3.2067418098449707, 2.7088210582733154, 1.9558219909667969]

--
Steven

Sep 3 '08 #8
process wrote:
is this faster btw? I guess big doesn't help, it's only retrieved once
anyway? But is rows retrieved in every loop? the python interpreter
aint too smart?

def getPixels(fileName):
im = PIL.Image.open(fileName)
colors = []
r, c = im.size
big = range(0, c)
rows = range(0, r)
for y in big:
row = []
for x in rows:
color = im.getpixel((x,y))
row.append(color)
colors.append(row)
return numpy.array(colors)
you'd probably get more done if you read the replies you get a bit more
carefully. Robert Kern suggesting using numpy.asarray earlier:

def getPixels(fileName):
im = PIL.Image.open(fileName)
return numpy.asarray(im)

if you want to work with pixels on the Python level, use im.getdata() or
the pixel access object returned by im.load().

</F>

Sep 3 '08 #9
Steven D'Aprano wrote:
On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote:
>ssecorp wrote:
>>or why does this take so god damn long time?
Several reasons. One of which is that try: except: is slow.


I beg to differ. Setting up a try...except block is very fast. Here's an
example in Python 2.5:

>>>from timeit import Timer
Timer('len("abc")').repeat()
[0.27346706390380859, 0.1530919075012207, 0.14886784553527832]
>>>Timer('''try:
... len("abc")
... except:
... pass
... ''').repeat()
[0.27847194671630859, 0.19191384315490723, 0.19077491760253906]

The difference (approx 0.04 microseconds) applicable to setting up the
try...except block is trivial, of the same magnitude as a pass statement:
>>>Timer('pass').repeat()
[0.059719085693359375, 0.060056924819946289, 0.059512138366699219]
However, *catching* the exception may be relatively slow:
>>>Timer('''try:
... len(abc) # raise a NameError
... except:
... pass
... ''').repeat()
[3.2067418098449707, 2.7088210582733154, 1.9558219909667969]
You're right. My mistake. I was misremembering Guido's old essay about try:
except: versus if: else:.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Sep 3 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: White Wolf | last post by:
Hi, I cannot believe my eyes, but so far I could not find out what is the name of the construct, which is built from one try block and the catch clauses (handlers). I am not looking for a...
11
by: kaeli | last post by:
Hey all, I'd like to start using the try/catch construct in some scripts. Older browsers don't support this. What's the best way to test for support for this construct so it doesn't kill...
11
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
40
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
23
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally...
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.