简体   繁体   中英

Tkinter image display (with [converted] NumPy array)

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!

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM