Re: [Numpy-discussion] display numpy array as image

2007-12-03 Thread Stefan van der Walt
Hi Zach

Attached is some code for removing radial distortion from images.  It
shows how to draw lines based on user input using matplotlib.  It is
not suited for a big application, but useful for demonstrations.

Try it on

  http://mentat.za.net/results/window.jpg

Regards
Stéfan

On Thu, Nov 29, 2007 at 11:59:05PM -0500, Zachary Pincus wrote:
 Thanks for the suggestions, everyone! All very informative and most  
 helpful.
 
 For what it's worth, here's my application: I'm building a tool for  
 image processing which needs some manual input in a few places (e.g.  
 user draws a few lines). The images are greyscale images with 12-14  
 bits of dynamic range (from a microscope), so I need to have some  
 basic brightness/contrast/gamma controls, as well as allowing basic  
 drawing on the image to get the needed user input. It looks like GL  
 or wx will be best suited here, I think? (I presume that python/numpy/ 
 [GL|wx] can keep up with things like dragging a slider to change  
 brightness/contrast/other LUT changes, as long as I code reasonably.)
 
 Anyhow, thanks for all the input,
 
 Zach
Remove radial distortion.

Author: Stefan van der Walt
Date: 2006


import scipy as S
import scipy.optimize
import scipy.ndimage

import pylab as P
import numpy as N
import math
import sys

class RadialDistortionInterface:
Mouse interaction interface for radial distortion removal.


def __init__(self, img):
  imshape = img.shape
  self.figure = P.imshow(img, extent=(0,imshape[1],imshape[0],0))
  P.title('Removal of radial distortion')
  P.xlabel('Select sets of three points with left mouse button,\nclick right button to process.')
  
  P.connect('button_press_event', self.button_press)
  P.connect('motion_notify_event', self.mouse_move)

  self.img = N.atleast_3d(img)
  self.points = []
  self.centre = ((N.array(self.img.shape)-1)/2.)[:2][::-1]
  self.height = imshape[0]
  self.width = imshape[1]
  
  self.make_cursorline()
  self.figure.axes.set_autoscale_on(False)

  P.show()
  P.close()
  
def make_cursorline(self):
self.cursorline, = P.plot([0],[0],'r:+',
  linewidth=2,markersize=15,markeredgecolor='b')

def button_press(self,event):
Register mouse clicks.


if (event.button == 1 and event.xdata and event.ydata):
self.points.append((event.xdata,event.ydata))
print Coordinate entered: (%f,%f) % (event.xdata, event.ydata)

if len(self.points) % 3 == 0:
P.gca().lines.append(self.cursorline)
self.make_cursorline()

if (event.button != 1 and len(self.points) = 3):
print Removing distortion...
P.gca().lines = []
P.draw()
self.remove_distortion()
self.points = []

def mouse_move(self,event):
Handle cursor drawing.


pt_sets,pts_last_set = divmod(len(self.points),3)
pts = N.zeros((3,2))
if pts_last_set  0:
# Line follows up to 3 clicked points:
pts[:pts_last_set] = self.points[-pts_last_set:]
# The last point of the line follows the mouse cursor
pts[pts_last_set:] = [event.xdata,event.ydata]
self.cursorline.set_data(pts[:,0],pts[:,1])
P.draw()

def stackcopy(self,a,b):
a[:,:,0] = a[:,:,1] = ... = b
if a.ndim == 3:
a.transpose().swapaxes(1,2)[:] = b
else:
a[:] = b

def remove_distortion(self,reshape=True):
def radii_tf(x,y,p):
Radially distort coordinates.

Given a coordinate (x,y), apply the radial distortion defined by

L(r) = 1 + p[2]r + p[3]r^2 + p[4]r^3

where

r = sqrt((x-p[0])^2 + (y-p[1])^2)

so that

x' = L(r)x   and   y' = L(r)y

Inputs:
x,y -- Coordinate
p[0],p[1] -- Distortion centre
p[2],p[3],p[4] -- Distortion parameters

Outputs:
x', y'


x = x - p[0]
y = y - p[1]
r = N.sqrt(x**2 + y**2)
f = 1 + p[2]*r + p[3]*r**2 + p[4]*r**3
return x*f + p[0], y*f + p[1]

def height_difference(p):
Measure deviation of distorted data points from straight line.


out = 0
for sets in 3*N.arange(len(self.points)/3):
pts = N.array(self.points[sets:sets+3])
x,y = radii_tf(pts[:,0],pts[:,1],p)

# Find point on line (point0 - point2) closest to point1 (midpoint)
u0 = ((x[0]-x[2])**2 + (y[0]-y[2])**2)
if u0 

Re: [Numpy-discussion] display numpy array as image

2007-12-03 Thread Zachary Pincus
Hi Stéfan,

Thanks -- I hadn't realized matplotlib's user-interaction abilities  
were that sophisticated! I'll definitely give that route a shot.

Zach


On Dec 3, 2007, at 9:46 AM, Stefan van der Walt wrote:

 Hi Zach

 Attached is some code for removing radial distortion from images.  It
 shows how to draw lines based on user input using matplotlib.  It is
 not suited for a big application, but useful for demonstrations.

 Try it on

   http://mentat.za.net/results/window.jpg

 Regards
 Stéfan

 On Thu, Nov 29, 2007 at 11:59:05PM -0500, Zachary Pincus wrote:
 Thanks for the suggestions, everyone! All very informative and most
 helpful.

 For what it's worth, here's my application: I'm building a tool for
 image processing which needs some manual input in a few places (e.g.
 user draws a few lines). The images are greyscale images with 12-14
 bits of dynamic range (from a microscope), so I need to have some
 basic brightness/contrast/gamma controls, as well as allowing basic
 drawing on the image to get the needed user input. It looks like GL
 or wx will be best suited here, I think? (I presume that python/ 
 numpy/
 [GL|wx] can keep up with things like dragging a slider to change
 brightness/contrast/other LUT changes, as long as I code reasonably.)

 Anyhow, thanks for all the input,

 Zachradial.py
 ___
 Numpy-discussion mailing list
 Numpy-discussion@scipy.org
 http://projects.scipy.org/mailman/listinfo/numpy-discussion

___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image (Giorgio F. Gilestro)

2007-12-01 Thread Hans Meine
On Freitag 30 November 2007, Joe Harrington wrote:
 I was misinformed about the status of numdisplay's pages.  The package
 is available as both part of stsci_python and independently, and its
 (up-to-date) home page is here:

 http://stsdas.stsci.edu/numdisplay/

I had a look at ds9/numdisplay, and as a summary, I found a nice viewer for 
scalar images with colormap support, and x/y projections.

What I missed though is the display of RGB images.  It looks as if ds9 was 
capable of doing so (I could add frames of RGB type), but I did not find a 
way to feed them with data.  numdisplay.display(myarray) seems to only 
support 2D-arrays.

Ciao, /  /.o.
 /--/ ..o
/  / ANS  ooo


signature.asc
Description: This is a digitally signed message part.
___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image (Giorgio F. Gilestro)

2007-11-30 Thread Joe Harrington
I was misinformed about the status of numdisplay's pages.  The package
is available as both part of stsci_python and independently, and its
(up-to-date) home page is here:

http://stsdas.stsci.edu/numdisplay/

Googling numdisplay finds that page.

My apologies to those inconvenienced by my prior post.

Note that there is practical documentation and examples of how to use it
for astronomical image display in the Data Analysis Tutorial:

http://www.scipy.org/wikis/topical_software/Tutorial

--jh--


___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Giorgio F. Gilestro
I am not sure I got what you mean but I am using PIL to convert arrays 
to images and viceversa
see http://mail.python.org/pipermail/image-sig/2006-September/004099.html
I embed bmps using wxpython.

Zachary Pincus wrote:
 Hello all,

 I'm curious if people have experience with / preferences for how to  
 display a numpy array onscreen as an image.

 Pyglet looks relatively easy -- you can feed an image buffer object  
 with a string or a ctypes pointer. I presume getting a string from an  
 array is plenty fast, but the ctypes pointer option is intriguing as  
 it allows for dealing with simple strided arrays (the image objects  
 allow for an arbitrary number of bytes between rows). Is it possible  
 to get a ctypes pointer to the beginning of the array buffer from  
 numpy without too much ugliness?

 wxPython looks pretty easy too, as there are facilities for getting  
 pixels from a buffer. Does anyone have any experience with these? Are  
 there ways of allowing a numpy array and a wxPython image to point to  
 the same memory?

 Anyhow, these are specific questions, but I'd also appreciate any  
 general thoughts about good approaches for getting pixels from numpy  
 arrays onscreen.

 Thanks,

 Zach
 ___
 Numpy-discussion mailing list
 Numpy-discussion@scipy.org
 http://projects.scipy.org/mailman/listinfo/numpy-discussion
   


-- 
[EMAIL PROTECTED]
http://www.cafelamarck.it


___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Angus McMorland
On 30/11/2007, Zachary Pincus [EMAIL PROTECTED] wrote:
 Hello all,

 I'm curious if people have experience with / preferences for how to
 display a numpy array onscreen as an image.

I'm not sure if you're after anything specific, but a very convenient
way to show 2-D arrays on screen is matplotlib (mpl), which is the
recommended graphical interface to numpy. With the pylab interface to
mpl, the command is as simple as
pylab.imshow(arr)
or
pylab.matshow(arr)
for slightly different axis behaviour.

Angus.
-- 
AJC McMorland, PhD Student
Physiology, University of Auckland
___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Joshua Lippai
On Nov 29, 2007 2:32 PM, Zachary Pincus [EMAIL PROTECTED] wrote:
 Hello all,

 I'm curious if people have experience with / preferences for how to
 display a numpy array onscreen as an image.

 Pyglet looks relatively easy -- you can feed an image buffer object
 with a string or a ctypes pointer. I presume getting a string from an
 array is plenty fast, but the ctypes pointer option is intriguing as
 it allows for dealing with simple strided arrays (the image objects
 allow for an arbitrary number of bytes between rows). Is it possible
 to get a ctypes pointer to the beginning of the array buffer from
 numpy without too much ugliness?

 wxPython looks pretty easy too, as there are facilities for getting
 pixels from a buffer. Does anyone have any experience with these? Are
 there ways of allowing a numpy array and a wxPython image to point to
 the same memory?

 Anyhow, these are specific questions, but I'd also appreciate any
 general thoughts about good approaches for getting pixels from numpy
 arrays onscreen.

 Thanks,

 Zach
 ___
 Numpy-discussion mailing list
 Numpy-discussion@scipy.org
 http://projects.scipy.org/mailman/listinfo/numpy-discussion


Have you tried the matplotlib/pylab module? It has pretty simple ways
of doing what you're thinking of if I'm understanding your intent
correctly..

Josh
___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Christopher Barker

Zachary Pincus wrote:
wxPython looks pretty easy too, as there are facilities for getting  
pixels from a buffer. Does anyone have any experience with these? 


some.

Are  
there ways of allowing a numpy array and a wxPython image to point to  
the same memory?


yup. You can build a wxImage from a buffer, and numpy provides a buffer 
interface, so they end up with them sharing the same memory, as long as 
your numpy array is contiguous 24 rgb.


I've enclosed a sample that generates a wx.Image from a numpy array, 
then every time you push the button, the array is altered in-place, and 
you can see the image change.


( think you need at least wxPython 2.8 for this to work)

-Chris








--
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/ORR(206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115   (206) 526-6317   main reception

[EMAIL PROTECTED]
#!/usr/bin/env python2.5


a small test of initializing a wxImage from a numpy array



import wx
import numpy as N
import numpy.random as rand

class ImagePanel(wx.Panel):
 
A very simple panel for displaying a wx.Image

def __init__(self, image, *args, **kwargs):
wx.Panel.__init__(self, *args, **kwargs)

self.image = image
self.Bind(wx.EVT_PAINT, self.OnPaint)

def OnPaint(self, event):
dc = wx.PaintDC(self)
dc.DrawBitmap(wx.BitmapFromImage(self.image), 0, 0)


class DemoFrame(wx.Frame):
 This window displays a button 
def __init__(self, title = Micro App):
wx.Frame.__init__(self, None , -1, title)

MenuBar = wx.MenuBar()
FileMenu = wx.Menu()

item = FileMenu.Append(wx.ID_ANY, text = Open)
self.Bind(wx.EVT_MENU, self.OnOpen, item)

item = FileMenu.Append(wx.ID_PREFERENCES, text = Preferences)
self.Bind(wx.EVT_MENU, self.OnPrefs, item)

item = FileMenu.Append(wx.ID_EXIT, text = Exit)
self.Bind(wx.EVT_MENU, self.OnQuit, item)

MenuBar.Append(FileMenu, File)

HelpMenu = wx.Menu()

item = HelpMenu.Append(wx.ID_HELP, Test Help,
Help for this simple test)
self.Bind(wx.EVT_MENU, self.OnHelp, item)

## this gets put in the App menu on OS-X
item = HelpMenu.Append(wx.ID_ABOUT, About,
More information About this program)
self.Bind(wx.EVT_MENU, self.OnAbout, item)
MenuBar.Append(HelpMenu, Help)

self.SetMenuBar(MenuBar)

btn = wx.Button(self, label = NewImage)
btn.Bind(wx.EVT_BUTTON, self.OnNewImage )

self.Bind(wx.EVT_CLOSE, self.OnQuit)

##Create numpy array, and image from it
w = h = 200
self.array = rand.randint(0, 255, (3, w, h)).astype('uint8')
print self.array
image = wx.ImageFromBuffer(w, h, self.array)
#image = wx.Image(Images/cute_close_up.jpg)
self.Panel = ImagePanel(image, self)

sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 5)
sizer.Add(self.Panel, 1, wx.GROW)

self.SetSizer(sizer)

def OnNewImage(self, event=None):

create a new image by changing underlying numpy array

self.array *= 1.2
self.Panel.Refresh()


def OnQuit(self,Event):
self.Destroy()

def OnAbout(self, event):
dlg = wx.MessageDialog(self, This is a small program to test\n
 the use of menus on Mac, etc.\n,
About Me, wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()

def OnHelp(self, event):
dlg = wx.MessageDialog(self, This would be help\n
 If there was any\n,
Test Help, wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()

def OnOpen(self, event):
dlg = wx.MessageDialog(self, This would be an open Dialog\n
 If there was anything to open\n,
Open File, wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()

def OnPrefs(self, event):
dlg = wx.MessageDialog(self, This would be an preferences Dialog\n
 If there were any preferences to set.\n,
Preferences, wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()

app = wx.App(False)
frame = DemoFrame()
frame.Show()
app.MainLoop()





___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Robert Kern
Zachary Pincus wrote:
 Hello all,
 
 I'm curious if people have experience with / preferences for how to  
 display a numpy array onscreen as an image.
 
 Pyglet looks relatively easy -- you can feed an image buffer object  
 with a string or a ctypes pointer. I presume getting a string from an  
 array is plenty fast, but the ctypes pointer option is intriguing as  
 it allows for dealing with simple strided arrays (the image objects  
 allow for an arbitrary number of bytes between rows). Is it possible  
 to get a ctypes pointer to the beginning of the array buffer from  
 numpy without too much ugliness?

In [16]: from numpy import *

In [17]: a = arange(10)

In [18]: dir(a.ctypes)
Out[18]:
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__str__',
 '__weakref__',
 '_arr',
 '_as_parameter_',
 '_ctypes',
 '_data',
 '_zerod',
 'data',
 'data_as',
 'get_as_parameter',
 'get_data',
 'get_shape',
 'get_strides',
 'shape',
 'shape_as',
 'strides',
 'strides_as']

In [22]: import ctypes

In [24]: a.ctypes.data_as(ctypes.POINTER(ctypes.c_long))
Out[24]: ctypes.LP_c_long object at 0x1b353a0

In [25]: a.ctypes.get_shape()
Out[25]: numpy.core._internal.c_long_Array_1 object at 0x1c096c0

In [26]: a.ctypes.get_strides()
Out[26]: numpy.core._internal.c_long_Array_1 object at 0x1c09710

In [27]: a.ctypes.get_as_parameter()
Out[27]: c_void_p(27442576)


You might want to use the new ctypes-based OpenGL 3.0+ package. It has numpy
support a bit more directly. You can use Pyglet for its windowing and all of the
other surrounding infrastructure and use OpenGL directly for the drawing.

-- 
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
___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Zachary Pincus
Thanks for the suggestions, everyone! All very informative and most  
helpful.

For what it's worth, here's my application: I'm building a tool for  
image processing which needs some manual input in a few places (e.g.  
user draws a few lines). The images are greyscale images with 12-14  
bits of dynamic range (from a microscope), so I need to have some  
basic brightness/contrast/gamma controls, as well as allowing basic  
drawing on the image to get the needed user input. It looks like GL  
or wx will be best suited here, I think? (I presume that python/numpy/ 
[GL|wx] can keep up with things like dragging a slider to change  
brightness/contrast/other LUT changes, as long as I code reasonably.)

Anyhow, thanks for all the input,

Zach


On Nov 29, 2007, at 9:03 PM, Joe Harrington wrote:

 If you want to explore the array interactively, blink images, mess  
 with
 colormaps using the mouse, rescale the image values, mark regions, add
 labels, look at dynamic plots of rows and columns, etc., get the ds9
 image viewer and the xpa programs that come with it that allow it to
 communicate with other programs:

 ftp://sao-ftp.harvard.edu/pub/rd/ds9
 http://hea-www.harvard.edu/RD/ds9/index.html

 Then get the Python numdisplay package, which uses xpa.  You have  
 to get
 numdisplay from inside the stsci_python package:

 http://www.stsci.edu/resources/software_hardware/pyraf/stsci_python/ 
 current/download

 Just grab the numdisplay directory from within that.  Older  
 versions of
 numdisplay are standalone but don't work perfectly.  Beware, there are
 outdated web sites about numdisplay on the stsci site.  Don't google!

 Run ds9 before you load numdisplay.  Then you can send your python
 arrays to a real interactive data viewer at will.  There are even
 mechanisms to define physical coordinates mapped from the image
 coordinates.

 --jh--



___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] display numpy array as image

2007-11-29 Thread Joe Harrington
If you want to explore the array interactively, blink images, mess with
colormaps using the mouse, rescale the image values, mark regions, add
labels, look at dynamic plots of rows and columns, etc., get the ds9
image viewer and the xpa programs that come with it that allow it to
communicate with other programs:

ftp://sao-ftp.harvard.edu/pub/rd/ds9
http://hea-www.harvard.edu/RD/ds9/index.html

Then get the Python numdisplay package, which uses xpa.  You have to get
numdisplay from inside the stsci_python package:

http://www.stsci.edu/resources/software_hardware/pyraf/stsci_python/current/download

Just grab the numdisplay directory from within that.  Older versions of
numdisplay are standalone but don't work perfectly.  Beware, there are
outdated web sites about numdisplay on the stsci site.  Don't google!

Run ds9 before you load numdisplay.  Then you can send your python
arrays to a real interactive data viewer at will.  There are even
mechanisms to define physical coordinates mapped from the image
coordinates.

--jh--


___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion