4
votes

In short, I'd like to convert a ImageTk.PhotoImage object to either a Image (PIL) object or numpy array. Knowing that you can convert a Image (PIL) object to a numpy array with numpy.asarray(). I'm given a numpy array and can display it in Tkinter like:

 from Tkinter import *
 import numpy as np
 import Image, ImageTk

 def callback(event):
      # do some stuff with a numpy array
      # ideally, e.g.:
      x=event.x; y=event.y
      val=np.asarray(imgTk)[x,y]
      print val

 arr=np.ones([256,256])
 img=Image.fromarray(arr)
 imgTk=ImageTk.PhotoImage(img)

 t=Tk()
 l=Label(t)
 l.configure(image=imgTk)
 l.bind('<Motion>', callback)

 l.pack()
 t.mainloop()

But the part

 np.asarray(imgTk)

does not return a [256,256] array like I expected. There may be an even easier way to go about this (as you can see, I'm trying to print out the pixel value for a 2D numpy array, or "image", as I move the cursor over it). Maybe I can even display a numpy array or Image (PIL) object in Tkinter w/o using ImageTk, but I can't seem to find an answer to that either. Any suggestions appreciated. Thanks!

1
And do you know how to do the opposite? As in how to change numpy array image into a Tk Image so that I can display it using Tkinter? - praxmon

1 Answers

4
votes

Getting pixel data from an ImageTk instance is very inefficient, and you can't convert an ImageTk instance back to a PIL Image, but you can simply get the data from the original PIL Image or even the array with your coords.

Instead of:

val=np.asarray(imgTk)[x,y]

Use:

val=img.getpixel((x, y))