numpy - matplotlib.pyplot Event Handling: Linear Increase in Key-Press Dwell Time? -
i writing image processing module in python using matplotlib.pyplot , numpy backend. images largely in tiff format, code below uses tifffile convert 3d image file 4d array in numpy. below code aims move through z-plane of 3d image, 1 image @ time, using z , x hotkeys. problem quite interesting , can't figure out: time between event , action (pressing x , displaying z+1 image) gets twice long each event. timed it, results below: 1st z-press: 0.124 s 2nd z-prss: 0.250 s 3rd z-press: 0.4875 s
it bonafide linear increase, can't find in code bug be.
import matplotlib.pyplot plt import numpy np import tifffile tiff class image: def __init__ (self, fname): self.fname = fname self.fig = plt.figure() self.z = 0 self.ax = self.fig.add_subplot(111) self.npimg = tiff.imread(self.fname) self.plotimg() self.connect() def plotimg(self): plt.imshow(self.npimg[self.z][0]) plt.show() def connect(self): self.cidkeypress = self.fig.canvas.mpl_connect('key_press_event',self.keypress) def disconnect(self): self.fig.canvas.mpl_disconnect(self.cidkeypress) def keypress(self, event): if event.key == 'x': self.z += 1 self.plotimg() elif event.key == 'z': self.z -= 1 self.plotimg()
since didn't provide example file, can't test code. think problem is, call plt.imshow()
repeatedly. each time new axesimage
object added figure. why timings increase linearly.
so solution have 1 axesimage
object , update data. adapt __init__
, plotimg
follows:
def __init__ (self, fname): self.fname = fname self.fig = plt.figure() self.z = 0 self.ax = self.fig.add_subplot(111) self.npimg = tiff.imread(self.fname) self.pltim = plt.imshow(self.npimg[self.z][0]) self.connect() plt.show() def plotimg(self): self.pltim.set_data(self.npimg[self.z][0]) plt.draw()
beware: untested code!
edit:
difference between plt.imshow
, plt.show
:
despite similar name, different things: plt.imshow
plotting function, draws image current axes (similar plt.plot
, plt.scatter
, etc.) plt.show
however, dispays figure on screen , enters backends mainloop (i.e. blocks code). this answer explains in more detail
Comments
Post a Comment