473,718 Members | 2,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Slow Python - what can be done?

Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image.

for a 400 x 600 image, python takes about 30 seconds to run the
algorithm. This seems way to slow - I would expect it to run in a
matter of a few seconds. Here's the code: what should I do to speed
things up? I know I'm going to get a "do it in C/make a C extension"
but that defeats the purpose: I'd like to know what Python can do
here.

Thanks for your help.

from Tkinter import *
import Image
import ImageTk
from sys import exit
from math import sqrt

class Point:
# A Point in the plane
def __init__(self, int1, int2):
# Constructor
self.x = float(int1)
self.y = float(int2)
def __add__(self, other):
# Add two points
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
# Sub two points
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
# Either mult by a constant or dot product
if type(other) == float or type(other) == int:
return Point(self.x*ot her, self.y*other)
else:
return self.x*other.x + self.y*other.y
def __div__(self,ot her):
# division by a constant
if type(other) == float or type(other) == int:
return Point(self.x/other, self.y/other)
def __rmul__(self, other):
# multiplication by a constant
return Point(self.x*ot her, self.y*other)
def __rdiv__(self, other):
# division by a constant
return Point(other/self.x, other/self.y)
def __str__(self):
# printing represenation
return '(%s, %s)' % (self.x, self.y)
def length(self):
# regular length
return sqrt(pow(self.x , 2) + pow(self.y, 2))
def perpindicular(s elf):
# 90 deg rotation
return Point(self.y, -self.x)
def to_tuple(self):
# makes a tuple of ints
return (int(self.x), int(self.y))
class WarpLine:
# The lines used to warp the image
def __init__(self, x0, y0, x1, y1, id):
# Constructor - just two points - id not used yet.
self.id = 0
self.point1 = Point(x0, y0)
self.point2 = Point(x1, y1)
def __str__(self):
# Printing
return '%s->%s' % (self.point1, self.point2)
def length(self):
# Segment length
return sqrt(pow(self.p oint2.x-self.point1.x, 2) +
pow(self.point2 .y-self.point1.y, 2))
def getUV(self, point):
# v = shortest distance of point to line
# u = the parameterizatio n of the closest point from v
diff = (self.point2 - self.point1)
u = ((point - self.point1) * diff) / (diff * diff)

v = ((point - self.point1) * diff.perpindicu lar()) / sqrt(diff
* diff)

return u, v
def transformPoint( self, line, point):
# finds transform of point based on self and line
diff = (line.point2 - line.point1)
u, v = self.getUV(poin t)
return line.point1 + u * diff + (v * diff.perpindicu lar()) /
sqrt(diff * diff)

class Picture:
# A simple image class
def __init__(self, file):
# Load up an image
self.data = Image.open(file )
def in_bounds(self, pt):
# is point in our bounds?
if pt.x < 0 or pt.y < 0 or pt.x > self.data.size[0] - 1 or
pt.y > self.data.size[1] - 1:
return 0
else:
return 1
def warp(self, source, line1, line2):
# Do transformPoint on each pixel, save results
# This is the slow part of the program
dest = list(self.data. getdata())
src = source.data.get data()
for x in range(0, self.data.size[0] - 1):
for y in range(0, self.data.size[1] - 1):
xy = line1.transform Point(line2,
Point(x,y)).to_ tuple()

if self.in_bounds( Point(xy[0], xy[1])):
dest[x + y*self.data.siz e[0]] = src[xy[0] +
xy[1]*self.data.size[0]]

else:
dest[x + y*self.data.siz e[0]] = 0

self.data.putda ta(dest)
def show(self):
# show the image
root = Tk()
canvas = Canvas(root, width=self.data .size[0],
height=self.dat a.size[1])
canvas.pack()
photo = ImageTk.PhotoIm age(self.data)
disp = canvas.create_i mage(0, 0, anchor=NW, image=photo)
mainloop()
Jul 18 '05 #1
16 2586
In article <48************ **************@ posting.google. com>, Jason wrote:
Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image. # This is the slow part of the program
dest = list(self.data. getdata())
src = source.data.get data()
for x in range(0, self.data.size[0] - 1):
for y in range(0, self.data.size[1] - 1):


"For loops" are evil ;-) Though I'm not familiar with your algorithm, you
should investigate the Numeric/numarray package, which is designed to
do lots of number crunching fast. If you can cast your problem into
good Numeric form, you'll see a speedup of a factor of hundreds.

Mike

--
Dr. Michael Ressler
Research Scientist, Astrophysics Research Element, Jet Propulsion Laboratory
Email: re*****@cheetah .jpl.nasa.gov Phone: (818)354-5576
"A bad night at the telescope is still better than the best day at the office."
Jul 18 '05 #2
On 18 Mar 2004 09:43:19 -0800, se******@rocknr oll.umcs.maine. edu
(Jason) wrote:
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementati on of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.


My impression is that you should avoid the Point class. It's a pretty
trivial class, but each time it is instantiated or an instance
destroyed you get some overhead. Do that enough times and you get
speed issues. If you can live with tuples and non-member functions,
that may be some help.

Also, for the picture data itself, possibly you should look at the
numarray library. I haven't used it myself, but I suspect that it will
have lower overheads than a standard Python list.

http://www.pfdubois.com/numpy/
You also seem to be doing too much avoidable work in your inner loop.
For instance, you could swap your x and y loops, and calculate things
like y*self.data.siz e[0] once per row (rather than for every single
pixel). I imagine there are also aspects of the transform calculation
that could be done once per row to save time, though I haven't looked
that closely at what you are doing.
--
Steve Horne

steve at ninereeds dot fsnet dot co dot uk
Jul 18 '05 #3
"Jason" <se******@rockn roll.umcs.maine .edu> wrote in message
news:48******** *************** ***@posting.goo gle.com...
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

<code snipped>

Here's a couple of thoughts:

- Replace the implementation of WarpLine.length () from:
return sqrt(pow(self.p oint2.x-self.point1.x, 2) +
pow(self.point2 .y-self.point1.y, 2))
to
return math.hypot( (self.point2-self.point1).to _tuple() )

If length() is called repeatedly for a given WarpLine, then cache this
value in an instance variable, and reset it if transformPoint is ever
called.

- Fire up the hotshot profiler. It will tell you which functions really
need tuning. Even though you've identified the "slow part", there are
several function calls made from this segment, any of which could be the
real hot spot.

- Look into using psyco. It is *very* non-intrusive, and you may find you
can get some major speed-up. The simplest way to get started, after
installing psyco is, at the top of your module, add:
import pysco
psyco.full()
psyco can get in the way of hotshot line profiling. But you will still get
accurate counts and timing at a function call level.

- Your Point class does a lot of type checking when multiplying or dividing
by a constant. Is this worth the penalty you are paying every time these
functions get called? Oh, wait, I see that __mul__ may be multiplying by a
constant, or doing a dot product. If hotshot tells you this is a choke
point, you might rethink using this one method for both functions. Or at
least, reduce your type() calls by changing from:
if type(other) == float or type(other) == int:
return Point(self.x*ot her, self.y*other)
else:
return self.x*other.x + self.y*other.y
to:
if isinstance(othe r, Point):
return self.x*other.x + self.y*other.y
else:
return Point(self.x*ot her, self.y*other)

- If you are forced to comparing types instead of using isinstance, I think
'is' would be a bit better than '=='.

- Why does Point.to_tuple( ) return int's, although you use floats
throughout? Since it looks like you have set up Point to be immutable, can
you keep both a float and an int member value for x and y, so you don't have
to do extra conversions? Also, since WarpLine also appears to be immutable,
you should be able to cache diff and diff*diff (maybe call it diff2 or
diffSquared) - either initialize in the __init__ method, or compute lazily
when needed.

- Experience in other languages sometimes gets in your way when using
Python. Not sure if this has any performance impact, but
Picture.in_boun ds() can be made more Pythonic, as (also, double check use of
'<' vs '<='):

def in_bounds(self, pt):
return (0 <= pt.x <= self.data.size[0] and 0 <= pt.y <=
self.data.size[1])

- Another thing to get used to in Python that is unlike other languages is
the return of ordered pairs of values. Look at this code:
xy = line1.transform Point(line2, Point(x,y)).to_ tuple()

if self.in_bounds( Point(xy[0], xy[1])):
dest[x + y*self.data.siz e[0]] = src[xy[0] +
xy[1]*self.data.size[0]]
else:
dest[x + y*self.data.siz e[0]] = 0

You return a tuple, lets call it (transx, transy), representing the
transformed point, then create a new Point using the separate elements to
test for in_bounds-ness, and then access the individual pieces using [0] and
[1] accesses. Function calls are performance killers in Python, so avoid
them where possible. Try this instead:
transPt = line1.transform Point(line2, Point(x,y))
transx, transy = transPt.to_tupl e() # or even transx,
transy = transPt.x, transPt.y

if self.in_bounds( transPt):
dest[x + y*self.data.siz e[0]] = src[transx +
transy*self.dat a.size[0]]
else:
dest[x + y*self.data.siz e[0]] = 0

- You also reference self.data.size[0] *many* times, even though this is
invariant across all your nested loops. Store this in a local variable
before you start your outer for loop, call it something like "xsize". Then
replace every use of "self.data. size[0]" with "xsize". As an added bonus,
your code will start getting more readable.

- Your arithmetic operators can generate *lots* of temporary Point objects.
You can streamline some of this process by defining a __slots__ attribute at
the class level, listing the field names "x" and "y". This will keep Python
from allocating a dictionary for all possible attribute names and values for
every Point object created. Likewise for WarpLine.

HTH,
-- Paul
Jul 18 '05 #4
On Thu, 18 Mar 2004 09:43:19 -0800, Jason wrote:
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image.

for a 400 x 600 image, python takes about 30 seconds to run the
algorithm. This seems way to slow - I would expect it to run in a
matter of a few seconds. Here's the code: what should I do to speed
things up? I know I'm going to get a "do it in C/make a C extension"
but that defeats the purpose: I'd like to know what Python can do
here.

Thanks for your help.
[SNIP]


I can't try your prog because I have not Tkinter,
but I think this app would gain a lot in performances using psyco.
http://psyco.sourceforge.net/ <-- home
http://psyco.sourceforge.net/psycoguide/index.html <-- doc

The simplest way to use psyco is putting
import psyco
psyco.full()
after your imports.

Ciao,
Riccardo
--
-=Riccardo Galli=-

_,e.
s~ ``
~@. ideralis Programs
.. ol
`**~ http://www.sideralis.net
Jul 18 '05 #5

Jason> Here's the code: what should I do to speed things up?

Without considering your code, two suggestions come to mind. One, look at
PIL or Numeric. Perhaps one of them has a more efficient C-based Image
class or array class will will help. Two, if you're running on an Intel
Pentium-type processor (Windows or Linux), take a look at psyco.

http://www.pythonware.com/products/pil/
http://psyco.sourceforge.net/

If you don't have Intel hardware, you might consider PyInline or SciPy's
weave tool to easily inline bits of C code into your Python.

A quick look at your code suggests that you use a fair amount of abstraction
(nothing wrong with that), then throw it away:

xy = line1.transform Point(line2, Point(x,y)).to_ tuple()
if self.in_bounds( Point(xy[0], xy[1])):
...

In the above, you instantiate a Point using x and y, then pass it to
transformPoint( ) which returns new Point. You immediately discard that
point by calling .to_tuple(), then in the next statement create yet another
Point with those same coordinates. Why not just have transformPoint accept
a tuple and return a tuple or at least save the transformed Point for later
use?

Skip

Jul 18 '05 #6
Hello Jason,
I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow. Did you use hotshot to find *where* you spend the time?
class Point:
...

I've found out the Python's faster with native types.
One thing is to use a tuple for the point and have functions like
point_sub(p1, p2)

You can try and use Psyco, in several cases it gives a very big speedup.

HTH.
Miki
Jul 18 '05 #7
Thanks for the help - I wasn't aware of the profilers avilable for
Python.

My uber-abstraction is due to recently fleeing from C (abstraction
made hard) and Lisp (no workable GUI stuff) so I'm stuck in the
middle. Anyway, I appreciate the comments.

Jason
Jul 18 '05 #8
se******@rocknr oll.umcs.maine. edu (Jason) wrote in message news:<48******* *************** ****@posting.go ogle.com>...
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image.

for a 400 x 600 image, python takes about 30 seconds to run the
algorithm. This seems way to slow - I would expect it to run in a
matter of a few seconds. Here's the code: what should I do to speed
things up? I know I'm going to get a "do it in C/make a C extension"
but that defeats the purpose: I'd like to know what Python can do
here.


If you can't go with the mentioned compilers (psycho) or libraries
there is nothing else then writing C. Python is best at glueing code
together. Writing numerical or highly mathematical algorithms in
python will always result in 10000% overhead.

Maybe you want to look at GNU eiffel (smarteiffel).

Remember there is no silver bullet !
Jul 18 '05 #9
se******@rocknr oll.umcs.maine. edu (Jason) writes:
Thanks for the help - I wasn't aware of the profilers avilable for
Python.


You might abuse complex numbers for points (the lisp faq recommends
doing this), maybe it speeds things up. You might even save time (I
did not try this, but hardware operations might be cheaper than Python
procedure calls) by doing complex products and ignoring the imaginary
part of the result just to get quickly at stuff like
p1.x*p2.x-p1.y*p2.y.

If you come from the lisp world anyway, you might try STk or stklos
(schemes with OO and Tk (or GTK) bindings).

Ralf
--
GS d->? s:++>+++ a+ C++++ UL+++ UH++ P++ L++ E+++ W- N++ o-- K- w--- !O M- V-
PS+>++ PE Y+>++ PGP+ !t !5 !X !R !tv b+++ DI+++ D? G+ e++++ h+ r? y?
Jul 18 '05 #10

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

Similar topics

1
5862
by: Rami Saarinen | last post by:
I have been making a client-server type of software mainly on Linux and now I am trying to get it all work also on windows. However, I am having slight problems running the program in Windows 2000. I have tried Python 2.2.3 and the latest release 2.3.1 (?) If I have 2 clients and 1 server. The server listening some predefined port and all the sending (in client and server) is done by creating a new connection. On the beginning the client...
5
2208
by: Michael Mossey | last post by:
Runnng python 2.2 on HP-UX, I get intermittant slow startup. Sometimes python starts up in a small fraction of a second, and sometimes takes 3-5 seconds. This applies to any script I run, or just typing 'python' at the prompt. I also observed something similar on Linux. Any ideas what would cause *intermittant* slow startup? -Mike
1
2091
by: iviskic | last post by:
Hi, I'm doing an analysis of program code performance when written in python as oppose to other programming languages, and can't seem to figure out why is the call of functions so slow? Is a context being created and stored on stog each time, or does it uses references? How EXACTLY does it work? I've read the documentation, but it is written on a cooking-book principle, so it does not say clearly how it works, just that it does work.
0
1091
by: wout | last post by:
Hi there, I am fairly new to python, the problem is as follows: newnodes = {} for i in nodes: newnodes = i.coordinate is very slow, which is due to the dots, I know that for functions the dot lookup
50
5722
by: diffuser78 | last post by:
I have just started to learn python. Some said that its slow. Can somebody pin point the issue. Thans
3
2864
by: chrisperkins99 | last post by:
It seems to me that str.count is awfully slow. Is there some reason for this? Evidence: ######## str.count time test ######## import string import time import array s = string.printable * int(1e5) # 10**7 character string
25
3800
by: jwrweatherley | last post by:
I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site - http://projecteuler.net. So far it has not let me down, but it has proved surprisingly slow on one puzzle. The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p < 1000, is the number of solutions {a,b,c} maximised? Here's my...
57
2696
by: dongie.agnir | last post by:
I'm pretty new to Python, and even newer to Image/Video processing, and trying to get started on a project similar to GRL Vienna's laser marker. I found some sample code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, but after running the code with the included sample input file, it seems quite slow (1-2 seconds from start to finish to do the 800 by 600 gif image). Is there a better way to do color tracking, or is...
39
2870
by: cm_gui | last post by:
Python is slow. Almost all of the web applications written in Python are slow. Zope/Plone is slow, sloow, so very slooow. Even Google Apps is not faster. Neither is Youtube. Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster than Python. Okay, they probably use caching or some code compilation -- but Google Apps and those Zope sites probably also use caching. I've yet to see a web application written in...
0
8724
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9356
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9121
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9053
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4481
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4743
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3182
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2555
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2122
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.