Problem displaying Numeric Array as image
Les Schaffer
godzilla at netmeg.net
Sat Jun 17 11:48:24 EDT 2000
Eric Frey said:
> I a trying to display a floating point Numeric (NumPy) array as a
> grayscale image via Tkinter.
this example code works for me. its an amalgam of stuff i have found
on the net... normalize takes a floating point image and scales it to
1 and returns byte values suitable for a greyscale image. with a
little cleaning up this should do what you want......
les schaffer
==================================
#!/usr/bin/python
from Tkinter import *
from ImageTk import PhotoImage
import Image
from Numeric import *
from RandomArray import random
def normalize(a):
a = array(a, copy=1)
a = (a - min(a.flat))/(max(a.flat) - min(a.flat))
return ( a*254 ).astype('b')
def ArrayToImage(a, height=200, scale=1):
a = normalize(a)
i = Image.new("L", (a.shape[1], a.shape[0]), color=255)
i.fromstring(a.tostring())
if scale != 1:
i = i.resize((i.size[0]*scale, i.size[1]*scale))
return i
def ImageToArray(i):
a = fromstring(i.tostring(), 'b')
a.shape = i.im.size[1], i.im.size[0]
return a
class MatrixDisplay:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red",
command=frame.quit)
self.button.pack(side=TOP)
self.test_B = Button(frame, text="Update", command=self.update)
self.test_B.pack(side=TOP)
self.img = Image.new("L",(100,100))
self.photo = PhotoImage(image=self.img)
self.canvas = Canvas(frame, width=100, height=100)
self.canvas.create_image(0, 0, anchor=NW, image=self.photo)
self.canvas.pack()
def update(self):
ra = fromfunction(self.func, (101, 101))
#ra = random((101, 101))
self.img = ArrayToImage(ra)
#self.photo = PhotoImage(self.img)
self.photo.paste(self.img)
self.canvas.create_image(0, 0, anchor=NW, image=self.photo)
self.canvas.update()
def func(self, i,j):
return cos( 4*2*3.1415926*i / 100. ) * cos( 4*2*3.1415926*(j / 100. ))
root = Tk()
app = MatrixDisplay(root)
root.mainloop()
More information about the Python-list
mailing list