Re: using PIL for PCA analysis

2008-02-26 Thread harryos
>Paul McGuire  wrote
> # following approx fromhttp://www.dfanning.com/ip_tips/color2gray.html
> grayscale = lambda (R,G,B) : int(0.3*R + 0.59*G + 0.11*B)
> print [ [ grayscale(rgb) for rgb in row ] for row in sampledata ]


Paul
in PIL handbook ,they mention a Luma transform on page15, under the
im.convert() section..
L = R * 299/1000 + G * 587/1000 + B * 114/1000
is that not similar to what you mentioned?(I am newbie in this area..)
if i want to do an array of PIL image data i can use
img=Image.open("myimg.jpg") .convert("L")
pixelarray=img.getdata()

thus i guess i can build a matrix of a set of  images
is there something wrong in the way i do this above?may be i can use
that to find covariance matrix for the set of images?

H
-- 
http://mail.python.org/mailman/listinfo/python-list


how to create eigenface image

2008-02-27 Thread harryos
hi all
I am new to python and learning PCA method by reading up Turk&Petland
papers etc
while trying out PCA on a set of greyscale images using python, and
numpy I tried to create eigenvectors and facespace.

i have
 facesarray--- an NXP numpy.ndarray that contains data of images
   N=numof images,P=pixels in an image
avgarray --1XP array containing avg value for each pixel
 adjustedfaces=facesarray-avgarray
adjustedmatrix=matrix(adjustedfaces)
adjustedmatrix_trans=adjustedmatrix.transpose()
covariancematrix =adjustedmatrix*adjustedmatrix_trans
evalues,evect=eigh(covariancematrix)

after sorting such that most significant eigenvectors are selected
evectmatrix is now my eigenvectors matrix

here is a sample using 4X3 greyscale images

evalues
[ -1.85852801e-13   6.31143639e+02   3.31182765e+03   5.29077871e+03]
evect
[[ 0.5-0.06727772  0.6496399  -0.56871936]
 [ 0.5-0.77317718 -0.37697426  0.10043632]
 [ 0.5 0.27108233  0.31014514  0.76179023]
 [ 0.5 0.56937257 -0.58281078 -0.29350719]]

evectmatrix  (sorted according to largest evalue first)
[[-0.56871936  0.6496399  -0.06727772  0.5   ]
 [ 0.10043632 -0.37697426 -0.77317718  0.5   ]
 [ 0.76179023  0.31014514  0.27108233  0.5   ]
 [-0.29350719 -0.58281078  0.56937257  0.5   ]]



then i can create facespace by
facespace=evectmat*adjustedfaces

what i want to know is how i can create eigenface images .
when you mean an eigenvector ,is that a row of evectmatrix above?  is
evectmatrix[0] the eigenvector for first image and so on? I would
appreciate if someone can make this clear.

also
when i tried to make an image by
im=im = Image.new('L', (width,height))
im.putdata(evectmat[0])
im.save("eigenface0.jpg")

it created an image with all pixels dark with no details to see
the same occurrs if i use
im.putdata(facespace[0])
can someone tell me if i am doing it wrong..




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding euclidean distance,better code?

2008-03-28 Thread harryos
> The code is pretty legible as it is now. Anyway, using min() and a
> generator:
>
>

hi
is this calculated distance really Euclidean distance? When i checked
wikipedia http://en.wikipedia.org/wiki/Euclidean_distance
it shows a calculation involving sum of squares of the differences of
elements.Here in this code ,the sum of coordinates are used? is that a
different measure?

oharry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding euclidean distance,better code?

2008-03-28 Thread harryos

> the norm from which it is derived is called norm-1, or L1; the usual > 
> euclidean distance is derived from norm-2.

> If you only want to see if two things are "close enough", this provides a  
> faster measure than the euclidean distance.


thanks Gabriel for the detailed explanation..
if i were to calculate the euclidean distance in the above example how
should i go about it..?
should i replace
distance = abs(input_wk - weights[image, :])
with something else?
thanks again
oharry
-- 
http://mail.python.org/mailman/listinfo/python-list


how to list all installed modules

2009-02-18 Thread harryos
hi
Is there a way to list all the installed modules in my python
installation.I recently installed pygame and when i tried to import it
like
>>import pygame
it complained that no such module was found.I can see the pygame
directory in F:\Python25\Lib\site-packages in my machine,but am unable
to import the module.So I was wondering if there is a way to list all
the installed modules

any help much appreciated
thanks
harry
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to list all installed modules

2009-02-18 Thread harryos
On Feb 18, 9:42 pm, Peter Otten <[email protected]> wrote:
> >>> help("modules")

thanks Peter.That helped.
> Regarding the original problem, do you have multiple Python installations?
> If so, you may accidentally be running the "wrong" python.

I have only one installation.It shows all other modules.I will try
reinstalling .
regards,
harry

--
http://mail.python.org/mailman/listinfo/python-list


Re: how to list all installed modules

2009-02-19 Thread harryos
On Feb 18, 11:10 pm, Scott David Daniels 
> Are you running F:\Python25\python.exe (or F:\Python25\pythonw.exe)?
> open a command window (run cmd), and type:
>      C:\> python
>      ...
>      >>> import sys
>      >>> for dirname in  sys.path:
>              print sys.path
>
> I suspect something you see printed will surprise you.
> Either the banner, identifying a Python version you were
> not expecting, or perhaps a bunch of C:-based directories.
> If this does not help you decipher the problem, try running
>       python -v
> Python verbose mode (You will get a _lot_ of output).
> Then, when you (finally) get a ">>>" prompt, type:
>     >>> import pygame
> and you will see eaxctly what lookups are tried.


thanks Scott for the detailed reply..
I reinstalled python and pygame and now things are working..:-)
thanks  again
harry
--
http://mail.python.org/mailman/listinfo/python-list


ImageTk.Photoimage not displayed

2008-08-28 Thread harryos
hi
i am trying to display an image on a canvas in a gui made with Tkinter
widgets


class PhotoDisplay:
def __init__(self,parent):
self.mainframe = Frame(parent,background="grey")
.
#added a subframe to hold canvas and button

   self.canvFrame=Frame(self.mainframe,...)
   
   self.mycanvas=Canvas(self.canvFrame,...)
   ...

def okbuttonClick(self):
self.mycanvas.delete(ALL)
myimagename=...#get an imagefilename from somewhere..
self.showSelectedImage(myimagename)

def showSelectedImage(self,imageName):
myimg=ImageTk.PhotoImage(file=imageName)
imgtag=self.mycanvas.create_image(70,100,image=myimg)
self.mycanvas.update_idletasks()


when i click the button ,the image is displayed for a fraction of a
second on the canvas and disappears.I couldn't figure out why this is
happening.I am quite new to Tkinter and still going  thru Fredrik
Lundh's intro to tkinter..can someone tell me if i am doing sthing
wrong here?
thanks in advance
harry
--
http://mail.python.org/mailman/listinfo/python-list


class definition syntax

2008-08-29 Thread harryos
hi
i have seen some class definitions like

class MyClass(object):
def __init__(self):
   

what does the object keyword inside the braces in MyClass() mean?
Has it got any significance?

thanks in advance
harry
--
http://mail.python.org/mailman/listinfo/python-list


use of super

2010-01-19 Thread harryos
hi
I was going thru the weblog appln in practical django book by
bennet .I came across this

class Entry(Model):
def save(self):
dosomething()
super(Entry,self).save()

I couldn't make out why Entry and self are passed as arguments to super
().Can someone please explain?
thanks
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use of super

2010-01-19 Thread harryos
thanks Simon..I should have checked it
-- 
http://mail.python.org/mailman/listinfo/python-list


os.path.join doubt

2011-02-02 Thread harryos
In windows ,I tried this

p1 = "C:\Users\me\Documents"
p2 = "..\Pictures\images\my.jpg"

print os.path.join(p1,p2)
This gives
'C:\\Users\\me\\Documents\\..\\Pictures\\images\\my.jpg'

I expected I would get
'C:\\Users\\me\\Pictures\\images\\my.jpg'

I thought os.path.join would join the paths more intelligently..Any
idea why this happens ?
harry


-- 
http://mail.python.org/mailman/listinfo/python-list


elementwise multiplication of 2 lists of numbers

2010-09-20 Thread harryos
hi
I have 2 lists of numbers,say
x=[2,4,3,1]
y=[5,9,10,6]
I need to create another list containing
z=[2*5, 4*9, 3*10, 1*6]  ie =[10,36,30,6]

I did not want to use numpy or any Array types.I tried to implement
this in python .I tried the following

z=[]
for a,b in zip(x,y):
z.append(a*b)
This gives me the correct result.Still,Is this the correct way?
Or can this be done in a better way?

Any pointers most welcome,
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: elementwise multiplication of 2 lists of numbers

2010-09-20 Thread harryos
On Sep 20, 7:28 pm, Bruno  wrote:
>> A list comp comes to mind, as well as using itertools.izip

thanks Bruno,thanks Gary..
Should have thought of list comprehension..
Thanks for the pointer about izip

harry
-- 
http://mail.python.org/mailman/listinfo/python-list


tix problem in ubuntu karmic

2010-09-27 Thread harryos
hi

I posted this question in ubuntu users forum but no help was
forthcoming..
I hope someone can help me here.

I had been using  jaunty as o.s and was coding in python 2.6. While
using Tix widgets in my code I came across a bug as mentioned in

https://bugs.launchpad.net/ubuntu/+source/tix/+bug/371720

Also ,there was a suggested fix

http://skriticos.blogspot.com/2009/07/ubuntu-jaunty-904-python-tix-fi...

After that I began to get segmentation fault when I ran the code!!

So ,I  thought upgrading to karmic would help .But even after the
upgrade I am getting segmentation fault..I reinstalled python ,tk and
tix through synaptic..Still the problem persists.

The versions of packages installed  are

python   =2.6.4-0ubuntu3

python-tk =2.6.3-0ubuntu1

tix  =8.4.0-6ubuntu1

tix-dev =8.4.0-6ubuntu1

tk8.5  =8.5.7-1

tk8.4 =8.4.19-3

Can someone tell me how I can solve this problem?

thanks,
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


scheduler or infinite loop

2010-09-29 Thread harryos
hi
I am trying to write a program to read data from a site url.
The program must read the data from site every 5 minutes.

def get_data_from_site(pageurlstr):
h=urllib.urlopen(pageurlstr)
data=h.read()
process_data(data)

At first, I thought of using the sched module ,but then it doesn't
look right adding so many scheduler.enter() statements.The program is
supposed to execute the above function every
5 minutes  until the application is shut down by the user.

I created an infinite loop
while True:
print time.asctime()
get_data_from_site('http://somesite.com/')
time.sleep(300)

Is there a better way to do this?Any suggestions ,pointers most
welcome
thanks
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scheduler or infinite loop

2010-09-29 Thread harryos
thanks Frank
>
> Here is a technique that allows the loop to run in the background, in its
> own thread, leaving the main program to do other processing -
>
> import threading
>
> class DataGetter(threading.Thread):
>
-- 
http://mail.python.org/mailman/listinfo/python-list


singleton problems

2010-10-03 Thread harryos
hi
I have been trying out singleton design pattern implementations..I
wrote this,


class Singleton(object):
_instance = None
def __new__(self, *args, **kwargs):
if not self._instance:
self._instance = super(Singleton, self).__new__(self,
*args, **kwargs)
return self._instance


class Mysingle(Singleton):
def __init__(self,name):
self.name=name

if __name__=='__main__':
s1=Mysingle('john')
s2=Mysingle('jim')
s3=Mysingle('jeff')
print 's1=',s1,s1.name
print 's2=',s2,s2.name
print 's3=',s3,s3.name

This is the result I got
s1= <__main__.Mysingle object at 0xb776492c> jeff
s2= <__main__.Mysingle object at 0xb776492c> jeff
s3= <__main__.Mysingle object at 0xb776492c> jeff
/home/dev/eclipse_workspace/pylearn/src/designpatterns.py:11:
DeprecationWarning: object.__new__() takes no parameters
  self._instance = super(Singleton, self).__new__(self, *args,
**kwargs)

shouldn't the name of s1,s2,s3 be 'john' instead of 'jeff'?
Also,how do I correct the deprecation problem?Can somebody comment?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: singleton problems

2010-10-03 Thread harryos
thanks Steven..that was very helpful..thanks a lot
harry
> Since __new__ is called before the instance exists, it doesn't receive an
> instance as the first argument. Instead it receives the class. While you
> can call the parameter anything you like, it is conventional to call it
> cls rather than self.
>
>
> Try this instead:
>
> class Singleton(object):
>     _instance = None
>     def __new__(cls, *args, **kwargs):
>         if not cls._instance:
>             cls._instance = super(Singleton, self).__new__(cls)
>             # or if you prefer: object.__new__(cls)
>         return cls._instance
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: singleton problems

2010-10-03 Thread harryos

thanks Arnold..that made it quite clear
harry
On Oct 3, 4:11 pm, Arnaud Delobelle  wrote:
> Arnaud Delobelle  writes:
>
-- 
http://mail.python.org/mailman/listinfo/python-list


how to handle network failures

2010-10-08 Thread harryos
hi
I  am trying to write a DataGrabber which reads some data from given
url..I made DataGrabber as a Thread and want to wait for some interval
of time in case there is a network failure that prevents read().
I am not very sure how to implement this

class DataGrabber(threading.Thread):
def __init__(self,url):
threading.Thread.__init__(self)
self.url=url
def run(self):
data=self.get_page_data()
process_data(data)

def get_page_data():
try:
f=urllib.urlopen(self.url)
data=f.read(1024)
except IOError:
#wait for some time and try again
time.sleep(120)
data=self.get_page_data()
return data

Is this the way to  implement the part where the thread waits and
reads the  data again? Will this handle network failures?Can somebody
please help?

thanks
harry


-- 
http://mail.python.org/mailman/listinfo/python-list


how to find difference in number of characters

2010-10-09 Thread harryos
hi
I am trying to write a compare method which takes two strings and find
how many characters have changed.


def compare_strings(s1,s2):
pass


text1="goat milk"
text2="cow milk"
print compare_strings(text1,text2)

This must give 3 ,since 3 characters are changed between strings.I was
advised to use levenshtein algorithm ..but then the matrix ops take a
long time for nontrivial strings of say 2 characters ..Can this
comparison be implemented using difflib module?..I am at a loss as to
how to implement this using difflib  .Is there some way I can get the
difference as a number ?
Can somebody help?
thanks
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to find difference in number of characters

2010-10-09 Thread harryos
On Oct 9, 2:45 pm, Peter Otten <[email protected]> wrote:

>
> What would be an acceptable time?
>

Thanks for the reply Peter,
I was using python functions I came across the net..not cpython
implementations..Probably my low config machine is also to blame..(I
am no expert at judging algorithm performance either),but is there a
way I can use difflib module to do this job?Even though I went through
the docs I couldn't make out how..

regards
harry

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to find difference in number of characters

2010-10-09 Thread harryos
On Oct 9, 4:52 pm, Peter Otten <[email protected]> wrote:

>
> You might get more/better answers if you tell us more about the context of
> the problem and add some details that may be relevant.
>
> Peter

I am trying to determine if a wep page is updated by x number of
characters..Mozilla firefox plugin 'update scanner' has a similar
functionality ..A user can specify the x ..I think this would be done
by reading from the same url at two different times and finding the
change in body text..I was wondering if difflib could offer something
in the way of determining the size of delta..
Thanks again for the reply..
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing for changes on a web page (was: how to find difference in number of characters)

2010-10-09 Thread harryos
On Oct 9, 5:41 pm, Stefan Behnel  wrote:

> "Number of characters" sounds like a rather useless measure here.

What I meant by number of characters was the number of edits happened
between the two versions..Levenshtein distance may be one way for
this..but I was wondering if difflib could do this
regards

harry
-- 
http://mail.python.org/mailman/listinfo/python-list


can I use more than one status condition name in imaplib.status()

2010-10-13 Thread harryos
Hi

In the signature of  of imaplib.status() method
MAP4.status(mailbox, names)
why is the 'names ' argument plural?Can I pass more than one name to
the method?
I can get correct  result when I call,
imapclient.status('Inbox', "(UNSEEN)")
or
imapclient.status('Inbox', "(RECENT)")

Is it possible to pass both these names ?
I tried,
imapclient.status('Inbox', "(UNSEEN,RECENT)")
which thows imaplib.error: STATUS command error: BAD ['Invalid
Command']

Any suggestions most welcome
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


imaplib AND date format

2010-10-14 Thread harryos
In imaplib.IMAP4.search() the search string SENTON can be used
'(SENTON 22-Jun-2010)'  .
But the RFC 2060 defines search key as
SENTON   Messages whose [RFC-822] Date: header is within the
 specified date.
and in RFC822 it is given as,
date=  1*2DIGIT month 2DIGIT; day month year
   ;  e.g.
20 Jun 82

The format 22 Jun 10 will cause aSEARCH command error:
 BAD ['Could not parse command']

Is this  deliberate or is it an anomaly ?
regards,
harry
-- 
http://mail.python.org/mailman/listinfo/python-list